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