Adding fields to the media uploader with jquery listeners

From Blackbone.js website:

render is the core function that your view should override, in order
to populate its element (this.el), with the appropriate HTML. The
convention is for render to always return this.

So, I have modified the code a little bit to add jQuery change listener.

function add_gallery_type_option(){
  ?>
  <script type="text/html" id="tmpl-my-custom-gallery-setting">
    <label class="setting">
      <span><?php _e('Gallery Style'); ?></span>
      <select class="js--gallery-style" data-setting="gallery_style">
        <option value="default"> Grid (default) </option>
        <option value="slider"> Slider </option>
      </select>
    </label>
  </script>

  <script>

    jQuery(document).ready(function(){
      _.extend(wp.media.gallery.defaults, {
        my_custom_attr: 'default_val'
      });

      // merge default gallery settings template with yours
      wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
        template: function(view){
          return wp.media.template('gallery-settings')(view)
               + wp.media.template('my-custom-gallery-setting')(view);
        },
        render: function() {
                wp.media.View.prototype.render.apply( this, arguments );

                jQuery(this.$('.js--gallery-style')).change(function(e)
                  {
                      alert(jQuery(this).val());
                  })
                return this;
            }
      });

    });

  </script>
  <?php
}
add_action('print_media_templates', 'add_gallery_type_option');

Leave a Comment