1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
var Attachments = wp.media.model.Attachments,
Selection;
/**
* wp.media.model.Selection
*
* A selection of attachments.
*
* @memberOf wp.media.model
*
* @class
* @augments wp.media.model.Attachments
* @augments Backbone.Collection
*/
Selection = Attachments.extend(/** @lends wp.media.model.Selection.prototype */{
/**
* Refresh the `single` model whenever the selection changes.
* Binds `single` instead of using the context argument to ensure
* it receives no parameters.
*
* @param {Array} [models=[]] Array of models used to populate the collection.
* @param {Object} [options={}]
*/
initialize: function( models, options ) {
/**
* call 'initialize' directly on the parent class
*/
Attachments.prototype.initialize.apply( this, arguments );
this.multiple = options && options.multiple;
this.on( 'add remove reset', _.bind( this.single, this, false ) );
},
/**
* If the workflow does not support multi-select, clear out the selection
* before adding a new attachment to it.
*
* @param {Array} models
* @param {Object} options
* @return {wp.media.model.Attachment[]}
*/
add: function( models, options ) {
if ( ! this.multiple ) {
this.remove( this.models );
}
/**
* call 'add' directly on the parent class
*/
return Attachments.prototype.add.call( this, models, options );
},
/**
* Fired when toggling (clicking on) an attachment in the modal.
*
* @param {undefined|boolean|wp.media.model.Attachment} model
*
* @fires wp.media.model.Selection#selection:single
* @fires wp.media.model.Selection#selection:unsingle
*
* @return {Backbone.Model}
*/
single: function( model ) {
var previous = this._single;
// If a `model` is provided, use it as the single model.
if ( model ) {
this._single = model;
}
// If the single model isn't in the selection, remove it.
if ( this._single && ! this.get( this._single.cid ) ) {
delete this._single;
}
this._single = this._single || this.last();
// If single has changed, fire an event.
if ( this._single !== previous ) {
if ( previous ) {
previous.trigger( 'selection:unsingle', previous, this );
// If the model was already removed, trigger the collection
// event manually.
if ( ! this.get( previous.cid ) ) {
this.trigger( 'selection:unsingle', previous, this );
}
}
if ( this._single ) {
this._single.trigger( 'selection:single', this._single, this );
}
}
// Return the single model, or the last model as a fallback.
return this._single;
}
});
module.exports = Selection;