Skip to content

Instantly share code, notes, and snippets.

@thomasgriffin
Created February 14, 2013 14:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasgriffin/4953041 to your computer and use it in GitHub Desktop.
Save thomasgriffin/4953041 to your computer and use it in GitHub Desktop.
My gift to you this Valentine's Day. Rendering custom attachment fields in the new media manager via Backbone.
/**
* The code below renders additional custom attachment fields into the
* new media manager.
*
* I am assuming you are using your own custom media modal frame. By
* extending the default Attachment.Details subview, we can append our
* custom fields to the default fields listed.
*
* In the initialize function, we ensure that our changes are always up
* to date by "listening" to our model's change event and updating the
* view when the event occurs.
*
* In the render function, we ensure that the parent render function is
* fired to display the default attachment fields. Once that is done,
* we detach the current view, append in our own custom fields via a
* custom script template (change "soliloquy-attachment-fields" to your
* own script template ID) and pass our model's JSON representation so that
* the "data" object can be localized to our instance.
*
* We then use this.model.fetch() to ensure that we have the most updated
* data from the server and then re-render our updated view.
*
* The "return this;" line is the preferred convention in all render functions
* in Backbone to maintain chainability.
* @link http://backbonejs.org/#View-render
*
* @author Thomas Griffin
*/
wp.media.view.Attachment.Details = wp.media.view.Attachment.Details.extend({
initialize: function(){
// Always make sure that our content is up to date.
this.model.on('change', this.render, this);
},
render: function(){
// Ensure that the main attachment fields are rendered.
wp.media.view.Attachment.prototype.render.apply(this, arguments);
// Detach the views, append our custom fields, make sure that our data is fully updated and re-render the updated view.
this.views.detach();
this.$el.append(wp.media.template('soliloquy-attachment-fields')(this.model.toJSON()));
this.model.fetch();
this.views.render();
// This is the preferred convention for all render functions.
return this;
}
});
@sc0ttkclark
Copy link

soliloquy-attachment-fields template example: https://gist.github.com/thomasgriffin/4953100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment