|
1 /* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */ |
|
2 /** |
|
3 * Backbone-relational.js 0.8.5 |
|
4 * (c) 2011-2013 Paul Uithol and contributors (https://github.com/PaulUithol/Backbone-relational/graphs/contributors) |
|
5 * |
|
6 * Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt. |
|
7 * For details and documentation: https://github.com/PaulUithol/Backbone-relational. |
|
8 * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone. |
|
9 */ |
|
10 ( function( undefined ) { |
|
11 "use strict"; |
|
12 |
|
13 /** |
|
14 * CommonJS shim |
|
15 **/ |
|
16 var _, Backbone, exports; |
|
17 if ( typeof window === 'undefined' ) { |
|
18 _ = require( 'underscore' ); |
|
19 Backbone = require( 'backbone' ); |
|
20 exports = module.exports = Backbone; |
|
21 } |
|
22 else { |
|
23 _ = window._; |
|
24 Backbone = window.Backbone; |
|
25 exports = window; |
|
26 } |
|
27 |
|
28 Backbone.Relational = { |
|
29 showWarnings: true |
|
30 }; |
|
31 |
|
32 /** |
|
33 * Semaphore mixin; can be used as both binary and counting. |
|
34 **/ |
|
35 Backbone.Semaphore = { |
|
36 _permitsAvailable: null, |
|
37 _permitsUsed: 0, |
|
38 |
|
39 acquire: function() { |
|
40 if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) { |
|
41 throw new Error( 'Max permits acquired' ); |
|
42 } |
|
43 else { |
|
44 this._permitsUsed++; |
|
45 } |
|
46 }, |
|
47 |
|
48 release: function() { |
|
49 if ( this._permitsUsed === 0 ) { |
|
50 throw new Error( 'All permits released' ); |
|
51 } |
|
52 else { |
|
53 this._permitsUsed--; |
|
54 } |
|
55 }, |
|
56 |
|
57 isLocked: function() { |
|
58 return this._permitsUsed > 0; |
|
59 }, |
|
60 |
|
61 setAvailablePermits: function( amount ) { |
|
62 if ( this._permitsUsed > amount ) { |
|
63 throw new Error( 'Available permits cannot be less than used permits' ); |
|
64 } |
|
65 this._permitsAvailable = amount; |
|
66 } |
|
67 }; |
|
68 |
|
69 /** |
|
70 * A BlockingQueue that accumulates items while blocked (via 'block'), |
|
71 * and processes them when unblocked (via 'unblock'). |
|
72 * Process can also be called manually (via 'process'). |
|
73 */ |
|
74 Backbone.BlockingQueue = function() { |
|
75 this._queue = []; |
|
76 }; |
|
77 _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, { |
|
78 _queue: null, |
|
79 |
|
80 add: function( func ) { |
|
81 if ( this.isBlocked() ) { |
|
82 this._queue.push( func ); |
|
83 } |
|
84 else { |
|
85 func(); |
|
86 } |
|
87 }, |
|
88 |
|
89 process: function() { |
|
90 while ( this._queue && this._queue.length ) { |
|
91 this._queue.shift()(); |
|
92 } |
|
93 }, |
|
94 |
|
95 block: function() { |
|
96 this.acquire(); |
|
97 }, |
|
98 |
|
99 unblock: function() { |
|
100 this.release(); |
|
101 if ( !this.isBlocked() ) { |
|
102 this.process(); |
|
103 } |
|
104 }, |
|
105 |
|
106 isBlocked: function() { |
|
107 return this.isLocked(); |
|
108 } |
|
109 }); |
|
110 /** |
|
111 * Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'change:<key>') |
|
112 * until the top-level object is fully initialized (see 'Backbone.RelationalModel'). |
|
113 */ |
|
114 Backbone.Relational.eventQueue = new Backbone.BlockingQueue(); |
|
115 |
|
116 /** |
|
117 * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel. |
|
118 * Handles lookup for relations. |
|
119 */ |
|
120 Backbone.Store = function() { |
|
121 this._collections = []; |
|
122 this._reverseRelations = []; |
|
123 this._orphanRelations = []; |
|
124 this._subModels = []; |
|
125 this._modelScopes = [ exports ]; |
|
126 }; |
|
127 _.extend( Backbone.Store.prototype, Backbone.Events, { |
|
128 /** |
|
129 * Create a new `Relation`. |
|
130 * @param {Backbone.RelationalModel} [model] |
|
131 * @param {Object} relation |
|
132 * @param {Object} [options] |
|
133 */ |
|
134 initializeRelation: function( model, relation, options ) { |
|
135 var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type ); |
|
136 if ( type && type.prototype instanceof Backbone.Relation ) { |
|
137 new type( model, relation, options ); // Also pushes the new Relation into `model._relations` |
|
138 } |
|
139 else { |
|
140 Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation ); |
|
141 } |
|
142 }, |
|
143 |
|
144 /** |
|
145 * Add a scope for `getObjectByName` to look for model types by name. |
|
146 * @param {Object} scope |
|
147 */ |
|
148 addModelScope: function( scope ) { |
|
149 this._modelScopes.push( scope ); |
|
150 }, |
|
151 |
|
152 /** |
|
153 * Remove a scope. |
|
154 * @param {Object} scope |
|
155 */ |
|
156 removeModelScope: function( scope ) { |
|
157 this._modelScopes = _.without( this._modelScopes, scope ); |
|
158 }, |
|
159 |
|
160 /** |
|
161 * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel' |
|
162 * for a model later in 'setupSuperModel'. |
|
163 * |
|
164 * @param {Backbone.RelationalModel} subModelTypes |
|
165 * @param {Backbone.RelationalModel} superModelType |
|
166 */ |
|
167 addSubModels: function( subModelTypes, superModelType ) { |
|
168 this._subModels.push({ |
|
169 'superModelType': superModelType, |
|
170 'subModels': subModelTypes |
|
171 }); |
|
172 }, |
|
173 |
|
174 /** |
|
175 * Check if the given modelType is registered as another model's subModel. If so, add it to the super model's |
|
176 * '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'. |
|
177 * |
|
178 * @param {Backbone.RelationalModel} modelType |
|
179 */ |
|
180 setupSuperModel: function( modelType ) { |
|
181 _.find( this._subModels, function( subModelDef ) { |
|
182 return _.find( subModelDef.subModels || [], function( subModelTypeName, typeValue ) { |
|
183 var subModelType = this.getObjectByName( subModelTypeName ); |
|
184 |
|
185 if ( modelType === subModelType ) { |
|
186 // Set 'modelType' as a child of the found superModel |
|
187 subModelDef.superModelType._subModels[ typeValue ] = modelType; |
|
188 |
|
189 // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'. |
|
190 modelType._superModel = subModelDef.superModelType; |
|
191 modelType._subModelTypeValue = typeValue; |
|
192 modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute; |
|
193 return true; |
|
194 } |
|
195 }, this ); |
|
196 }, this ); |
|
197 }, |
|
198 |
|
199 /** |
|
200 * Add a reverse relation. Is added to the 'relations' property on model's prototype, and to |
|
201 * existing instances of 'model' in the store as well. |
|
202 * @param {Object} relation |
|
203 * @param {Backbone.RelationalModel} relation.model |
|
204 * @param {String} relation.type |
|
205 * @param {String} relation.key |
|
206 * @param {String|Object} relation.relatedModel |
|
207 */ |
|
208 addReverseRelation: function( relation ) { |
|
209 var exists = _.any( this._reverseRelations, function( rel ) { |
|
210 return _.all( relation || [], function( val, key ) { |
|
211 return val === rel[ key ]; |
|
212 }); |
|
213 }); |
|
214 |
|
215 if ( !exists && relation.model && relation.type ) { |
|
216 this._reverseRelations.push( relation ); |
|
217 this._addRelation( relation.model, relation ); |
|
218 this.retroFitRelation( relation ); |
|
219 } |
|
220 }, |
|
221 |
|
222 /** |
|
223 * Deposit a `relation` for which the `relatedModel` can't be resolved at the moment. |
|
224 * |
|
225 * @param {Object} relation |
|
226 */ |
|
227 addOrphanRelation: function( relation ) { |
|
228 var exists = _.any( this._orphanRelations, function( rel ) { |
|
229 return _.all( relation || [], function( val, key ) { |
|
230 return val === rel[ key ]; |
|
231 }); |
|
232 }); |
|
233 |
|
234 if ( !exists && relation.model && relation.type ) { |
|
235 this._orphanRelations.push( relation ); |
|
236 } |
|
237 }, |
|
238 |
|
239 /** |
|
240 * Try to initialize any `_orphanRelation`s |
|
241 */ |
|
242 processOrphanRelations: function() { |
|
243 // Make sure to operate on a copy since we're removing while iterating |
|
244 _.each( this._orphanRelations.slice( 0 ), function( rel ) { |
|
245 var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); |
|
246 if ( relatedModel ) { |
|
247 this.initializeRelation( null, rel ); |
|
248 this._orphanRelations = _.without( this._orphanRelations, rel ); |
|
249 } |
|
250 }, this ); |
|
251 }, |
|
252 |
|
253 /** |
|
254 * |
|
255 * @param {Backbone.RelationalModel.constructor} type |
|
256 * @param {Object} relation |
|
257 * @private |
|
258 */ |
|
259 _addRelation: function( type, relation ) { |
|
260 if ( !type.prototype.relations ) { |
|
261 type.prototype.relations = []; |
|
262 } |
|
263 type.prototype.relations.push( relation ); |
|
264 |
|
265 _.each( type._subModels || [], function( subModel ) { |
|
266 this._addRelation( subModel, relation ); |
|
267 }, this ); |
|
268 }, |
|
269 |
|
270 /** |
|
271 * Add a 'relation' to all existing instances of 'relation.model' in the store |
|
272 * @param {Object} relation |
|
273 */ |
|
274 retroFitRelation: function( relation ) { |
|
275 var coll = this.getCollection( relation.model, false ); |
|
276 coll && coll.each( function( model ) { |
|
277 if ( !( model instanceof relation.model ) ) { |
|
278 return; |
|
279 } |
|
280 |
|
281 new relation.type( model, relation ); |
|
282 }, this ); |
|
283 }, |
|
284 |
|
285 /** |
|
286 * Find the Store's collection for a certain type of model. |
|
287 * @param {Backbone.RelationalModel} type |
|
288 * @param {Boolean} [create=true] Should a collection be created if none is found? |
|
289 * @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null |
|
290 */ |
|
291 getCollection: function( type, create ) { |
|
292 if ( type instanceof Backbone.RelationalModel ) { |
|
293 type = type.constructor; |
|
294 } |
|
295 |
|
296 var rootModel = type; |
|
297 while ( rootModel._superModel ) { |
|
298 rootModel = rootModel._superModel; |
|
299 } |
|
300 |
|
301 var coll = _.findWhere( this._collections, { model: rootModel } ); |
|
302 |
|
303 if ( !coll && create !== false ) { |
|
304 coll = this._createCollection( rootModel ); |
|
305 } |
|
306 |
|
307 return coll; |
|
308 }, |
|
309 |
|
310 /** |
|
311 * Find a model type on one of the modelScopes by name. Names are split on dots. |
|
312 * @param {String} name |
|
313 * @return {Object} |
|
314 */ |
|
315 getObjectByName: function( name ) { |
|
316 var parts = name.split( '.' ), |
|
317 type = null; |
|
318 |
|
319 _.find( this._modelScopes, function( scope ) { |
|
320 type = _.reduce( parts || [], function( memo, val ) { |
|
321 return memo ? memo[ val ] : undefined; |
|
322 }, scope ); |
|
323 |
|
324 if ( type && type !== scope ) { |
|
325 return true; |
|
326 } |
|
327 }, this ); |
|
328 |
|
329 return type; |
|
330 }, |
|
331 |
|
332 _createCollection: function( type ) { |
|
333 var coll; |
|
334 |
|
335 // If 'type' is an instance, take its constructor |
|
336 if ( type instanceof Backbone.RelationalModel ) { |
|
337 type = type.constructor; |
|
338 } |
|
339 |
|
340 // Type should inherit from Backbone.RelationalModel. |
|
341 if ( type.prototype instanceof Backbone.RelationalModel ) { |
|
342 coll = new Backbone.Collection(); |
|
343 coll.model = type; |
|
344 |
|
345 this._collections.push( coll ); |
|
346 } |
|
347 |
|
348 return coll; |
|
349 }, |
|
350 |
|
351 /** |
|
352 * Find the attribute that is to be used as the `id` on a given object |
|
353 * @param type |
|
354 * @param {String|Number|Object|Backbone.RelationalModel} item |
|
355 * @return {String|Number} |
|
356 */ |
|
357 resolveIdForItem: function( type, item ) { |
|
358 var id = _.isString( item ) || _.isNumber( item ) ? item : null; |
|
359 |
|
360 if ( id === null ) { |
|
361 if ( item instanceof Backbone.RelationalModel ) { |
|
362 id = item.id; |
|
363 } |
|
364 else if ( _.isObject( item ) ) { |
|
365 id = item[ type.prototype.idAttribute ]; |
|
366 } |
|
367 } |
|
368 |
|
369 // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179') |
|
370 if ( !id && id !== 0 ) { |
|
371 id = null; |
|
372 } |
|
373 |
|
374 return id; |
|
375 }, |
|
376 |
|
377 /** |
|
378 * Find a specific model of a certain `type` in the store |
|
379 * @param type |
|
380 * @param {String|Number|Object|Backbone.RelationalModel} item |
|
381 */ |
|
382 find: function( type, item ) { |
|
383 var id = this.resolveIdForItem( type, item ); |
|
384 var coll = this.getCollection( type ); |
|
385 |
|
386 // Because the found object could be of any of the type's superModel |
|
387 // types, only return it if it's actually of the type asked for. |
|
388 if ( coll ) { |
|
389 var obj = coll.get( id ); |
|
390 |
|
391 if ( obj instanceof type ) { |
|
392 return obj; |
|
393 } |
|
394 } |
|
395 |
|
396 return null; |
|
397 }, |
|
398 |
|
399 /** |
|
400 * Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'. |
|
401 * @param {Backbone.RelationalModel} model |
|
402 */ |
|
403 register: function( model ) { |
|
404 var coll = this.getCollection( model ); |
|
405 |
|
406 if ( coll ) { |
|
407 var modelColl = model.collection; |
|
408 coll.add( model ); |
|
409 this.listenTo( model, 'destroy', this.unregister, this ); |
|
410 model.collection = modelColl; |
|
411 } |
|
412 }, |
|
413 |
|
414 /** |
|
415 * Check if the given model may use the given `id` |
|
416 * @param model |
|
417 * @param [id] |
|
418 */ |
|
419 checkId: function( model, id ) { |
|
420 var coll = this.getCollection( model ), |
|
421 duplicate = coll && coll.get( id ); |
|
422 |
|
423 if ( duplicate && model !== duplicate ) { |
|
424 if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { |
|
425 console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model ); |
|
426 } |
|
427 |
|
428 throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" ); |
|
429 } |
|
430 }, |
|
431 |
|
432 /** |
|
433 * Explicitly update a model's id in its store collection |
|
434 * @param {Backbone.RelationalModel} model |
|
435 */ |
|
436 update: function( model ) { |
|
437 var coll = this.getCollection( model ); |
|
438 // This triggers updating the lookup indices kept in a collection |
|
439 coll._onModelEvent( 'change:' + model.idAttribute, model, coll ); |
|
440 |
|
441 // Trigger an event on model so related models (having the model's new id in their keyContents) can add it. |
|
442 model.trigger( 'relational:change:id', model, coll ); |
|
443 }, |
|
444 |
|
445 /** |
|
446 * Remove a 'model' from the store. |
|
447 * @param {Backbone.RelationalModel} model |
|
448 */ |
|
449 unregister: function( model ) { |
|
450 this.stopListening( model, 'destroy', this.unregister ); |
|
451 var coll = this.getCollection( model ); |
|
452 coll && coll.remove( model ); |
|
453 }, |
|
454 |
|
455 /** |
|
456 * Reset the `store` to it's original state. The `reverseRelations` are kept though, since attempting to |
|
457 * re-initialize these on models would lead to a large amount of warnings. |
|
458 */ |
|
459 reset: function() { |
|
460 this.stopListening(); |
|
461 this._collections = []; |
|
462 this._subModels = []; |
|
463 this._modelScopes = [ exports ]; |
|
464 } |
|
465 }); |
|
466 Backbone.Relational.store = new Backbone.Store(); |
|
467 |
|
468 /** |
|
469 * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events |
|
470 * are used to regulate addition and removal of models from relations. |
|
471 * |
|
472 * @param {Backbone.RelationalModel} [instance] Model that this relation is created for. If no model is supplied, |
|
473 * Relation just tries to instantiate it's `reverseRelation` if specified, and bails out after that. |
|
474 * @param {Object} options |
|
475 * @param {string} options.key |
|
476 * @param {Backbone.RelationalModel.constructor} options.relatedModel |
|
477 * @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids. |
|
478 * @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store. |
|
479 * @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate |
|
480 * the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs |
|
481 * {Backbone.Relation|String} type ('HasOne' or 'HasMany'). |
|
482 * @param {Object} opts |
|
483 */ |
|
484 Backbone.Relation = function( instance, options, opts ) { |
|
485 this.instance = instance; |
|
486 // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype |
|
487 options = _.isObject( options ) ? options : {}; |
|
488 this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation ); |
|
489 this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options ); |
|
490 |
|
491 this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type : |
|
492 Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type ); |
|
493 |
|
494 this.key = this.options.key; |
|
495 this.keySource = this.options.keySource || this.key; |
|
496 this.keyDestination = this.options.keyDestination || this.keySource || this.key; |
|
497 |
|
498 this.model = this.options.model || this.instance.constructor; |
|
499 this.relatedModel = this.options.relatedModel; |
|
500 if ( _.isString( this.relatedModel ) ) { |
|
501 this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel ); |
|
502 } |
|
503 |
|
504 if ( !this.checkPreconditions() ) { |
|
505 return; |
|
506 } |
|
507 |
|
508 // Add the reverse relation on 'relatedModel' to the store's reverseRelations |
|
509 if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) { |
|
510 Backbone.Relational.store.addReverseRelation( _.defaults( { |
|
511 isAutoRelation: true, |
|
512 model: this.relatedModel, |
|
513 relatedModel: this.model, |
|
514 reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation |
|
515 }, |
|
516 this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.) |
|
517 ) ); |
|
518 } |
|
519 |
|
520 if ( instance ) { |
|
521 var contentKey = this.keySource; |
|
522 if ( contentKey !== this.key && typeof this.instance.get( this.key ) === 'object' ) { |
|
523 contentKey = this.key; |
|
524 } |
|
525 |
|
526 this.setKeyContents( this.instance.get( contentKey ) ); |
|
527 this.relatedCollection = Backbone.Relational.store.getCollection( this.relatedModel ); |
|
528 |
|
529 // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. |
|
530 if ( this.keySource !== this.key ) { |
|
531 this.instance.unset( this.keySource, { silent: true } ); |
|
532 } |
|
533 |
|
534 // Add this Relation to instance._relations |
|
535 this.instance._relations[ this.key ] = this; |
|
536 |
|
537 this.initialize( opts ); |
|
538 |
|
539 if ( this.options.autoFetch ) { |
|
540 this.instance.fetchRelated( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} ); |
|
541 } |
|
542 |
|
543 // When 'relatedModel' are created or destroyed, check if it affects this relation. |
|
544 this.listenTo( this.instance, 'destroy', this.destroy ) |
|
545 .listenTo( this.relatedCollection, 'relational:add relational:change:id', this.tryAddRelated ) |
|
546 .listenTo( this.relatedCollection, 'relational:remove', this.removeRelated ) |
|
547 } |
|
548 }; |
|
549 // Fix inheritance :\ |
|
550 Backbone.Relation.extend = Backbone.Model.extend; |
|
551 // Set up all inheritable **Backbone.Relation** properties and methods. |
|
552 _.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, { |
|
553 options: { |
|
554 createModels: true, |
|
555 includeInJSON: true, |
|
556 isAutoRelation: false, |
|
557 autoFetch: false, |
|
558 parse: false |
|
559 }, |
|
560 |
|
561 instance: null, |
|
562 key: null, |
|
563 keyContents: null, |
|
564 relatedModel: null, |
|
565 relatedCollection: null, |
|
566 reverseRelation: null, |
|
567 related: null, |
|
568 |
|
569 /** |
|
570 * Check several pre-conditions. |
|
571 * @return {Boolean} True if pre-conditions are satisfied, false if they're not. |
|
572 */ |
|
573 checkPreconditions: function() { |
|
574 var i = this.instance, |
|
575 k = this.key, |
|
576 m = this.model, |
|
577 rm = this.relatedModel, |
|
578 warn = Backbone.Relational.showWarnings && typeof console !== 'undefined'; |
|
579 |
|
580 if ( !m || !k || !rm ) { |
|
581 warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm ); |
|
582 return false; |
|
583 } |
|
584 // Check if the type in 'model' inherits from Backbone.RelationalModel |
|
585 if ( !( m.prototype instanceof Backbone.RelationalModel ) ) { |
|
586 warn && console.warn( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).', this, i ); |
|
587 return false; |
|
588 } |
|
589 // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel |
|
590 if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) { |
|
591 warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).', this, rm ); |
|
592 return false; |
|
593 } |
|
594 // Check if this is not a HasMany, and the reverse relation is HasMany as well |
|
595 if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) { |
|
596 warn && console.warn( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.', this ); |
|
597 return false; |
|
598 } |
|
599 // Check if we're not attempting to create a relationship on a `key` that's already used. |
|
600 if ( i && _.keys( i._relations ).length ) { |
|
601 var existing = _.find( i._relations, function( rel ) { |
|
602 return rel.key === k; |
|
603 }, this ); |
|
604 |
|
605 if ( existing ) { |
|
606 warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.', |
|
607 this, k, i, existing ); |
|
608 return false; |
|
609 } |
|
610 } |
|
611 |
|
612 return true; |
|
613 }, |
|
614 |
|
615 /** |
|
616 * Set the related model(s) for this relation |
|
617 * @param {Backbone.Model|Backbone.Collection} related |
|
618 */ |
|
619 setRelated: function( related ) { |
|
620 this.related = related; |
|
621 |
|
622 this.instance.acquire(); |
|
623 this.instance.attributes[ this.key ] = related; |
|
624 this.instance.release(); |
|
625 }, |
|
626 |
|
627 /** |
|
628 * Determine if a relation (on a different RelationalModel) is the reverse |
|
629 * relation of the current one. |
|
630 * @param {Backbone.Relation} relation |
|
631 * @return {Boolean} |
|
632 */ |
|
633 _isReverseRelation: function( relation ) { |
|
634 return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key && |
|
635 this.key === relation.reverseRelation.key; |
|
636 }, |
|
637 |
|
638 /** |
|
639 * Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s). |
|
640 * @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model. |
|
641 * If not specified, 'this.related' is used. |
|
642 * @return {Backbone.Relation[]} |
|
643 */ |
|
644 getReverseRelations: function( model ) { |
|
645 var reverseRelations = []; |
|
646 // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array. |
|
647 var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] ); |
|
648 _.each( models || [], function( related ) { |
|
649 _.each( related.getRelations() || [], function( relation ) { |
|
650 if ( this._isReverseRelation( relation ) ) { |
|
651 reverseRelations.push( relation ); |
|
652 } |
|
653 }, this ); |
|
654 }, this ); |
|
655 |
|
656 return reverseRelations; |
|
657 }, |
|
658 |
|
659 /** |
|
660 * When `this.instance` is destroyed, cleanup our relations. |
|
661 * Get reverse relation, call removeRelated on each. |
|
662 */ |
|
663 destroy: function() { |
|
664 this.stopListening(); |
|
665 |
|
666 if ( this instanceof Backbone.HasOne ) { |
|
667 this.setRelated( null ); |
|
668 } |
|
669 else if ( this instanceof Backbone.HasMany ) { |
|
670 this.setRelated( this._prepareCollection() ); |
|
671 } |
|
672 |
|
673 _.each( this.getReverseRelations(), function( relation ) { |
|
674 relation.removeRelated( this.instance ); |
|
675 }, this ); |
|
676 } |
|
677 }); |
|
678 |
|
679 Backbone.HasOne = Backbone.Relation.extend({ |
|
680 options: { |
|
681 reverseRelation: { type: 'HasMany' } |
|
682 }, |
|
683 |
|
684 initialize: function( opts ) { |
|
685 this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange ); |
|
686 |
|
687 var related = this.findRelated( opts ); |
|
688 this.setRelated( related ); |
|
689 |
|
690 // Notify new 'related' object of the new relation. |
|
691 _.each( this.getReverseRelations(), function( relation ) { |
|
692 relation.addRelated( this.instance, opts ); |
|
693 }, this ); |
|
694 }, |
|
695 |
|
696 /** |
|
697 * Find related Models. |
|
698 * @param {Object} [options] |
|
699 * @return {Backbone.Model} |
|
700 */ |
|
701 findRelated: function( options ) { |
|
702 var related = null; |
|
703 |
|
704 options = _.defaults( { parse: this.options.parse }, options ); |
|
705 |
|
706 if ( this.keyContents instanceof this.relatedModel ) { |
|
707 related = this.keyContents; |
|
708 } |
|
709 else if ( this.keyContents || this.keyContents === 0 ) { // since 0 can be a valid `id` as well |
|
710 var opts = _.defaults( { create: this.options.createModels }, options ); |
|
711 related = this.relatedModel.findOrCreate( this.keyContents, opts ); |
|
712 } |
|
713 |
|
714 // Nullify `keyId` if we have a related model; in case it was already part of the relation |
|
715 if ( this.related ) { |
|
716 this.keyId = null; |
|
717 } |
|
718 |
|
719 return related; |
|
720 }, |
|
721 |
|
722 /** |
|
723 * Normalize and reduce `keyContents` to an `id`, for easier comparison |
|
724 * @param {String|Number|Backbone.Model} keyContents |
|
725 */ |
|
726 setKeyContents: function( keyContents ) { |
|
727 this.keyContents = keyContents; |
|
728 this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents ); |
|
729 }, |
|
730 |
|
731 /** |
|
732 * Event handler for `change:<key>`. |
|
733 * If the key is changed, notify old & new reverse relations and initialize the new relation. |
|
734 */ |
|
735 onChange: function( model, attr, options ) { |
|
736 // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange) |
|
737 if ( this.isLocked() ) { |
|
738 return; |
|
739 } |
|
740 this.acquire(); |
|
741 options = options ? _.clone( options ) : {}; |
|
742 |
|
743 // 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change |
|
744 // is the result of a call from a relation. If it's not, the change is the result of |
|
745 // a 'set' call on this.instance. |
|
746 var changed = _.isUndefined( options.__related ), |
|
747 oldRelated = changed ? this.related : options.__related; |
|
748 |
|
749 if ( changed ) { |
|
750 this.setKeyContents( attr ); |
|
751 var related = this.findRelated( options ); |
|
752 this.setRelated( related ); |
|
753 } |
|
754 |
|
755 // Notify old 'related' object of the terminated relation |
|
756 if ( oldRelated && this.related !== oldRelated ) { |
|
757 _.each( this.getReverseRelations( oldRelated ), function( relation ) { |
|
758 relation.removeRelated( this.instance, null, options ); |
|
759 }, this ); |
|
760 } |
|
761 |
|
762 // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated; |
|
763 // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'. |
|
764 // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet. |
|
765 _.each( this.getReverseRelations(), function( relation ) { |
|
766 relation.addRelated( this.instance, options ); |
|
767 }, this ); |
|
768 |
|
769 // Fire the 'change:<key>' event if 'related' was updated |
|
770 if ( !options.silent && this.related !== oldRelated ) { |
|
771 var dit = this; |
|
772 this.changed = true; |
|
773 Backbone.Relational.eventQueue.add( function() { |
|
774 dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true ); |
|
775 dit.changed = false; |
|
776 }); |
|
777 } |
|
778 this.release(); |
|
779 }, |
|
780 |
|
781 /** |
|
782 * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents' |
|
783 */ |
|
784 tryAddRelated: function( model, coll, options ) { |
|
785 if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well |
|
786 this.addRelated( model, options ); |
|
787 this.keyId = null; |
|
788 } |
|
789 }, |
|
790 |
|
791 addRelated: function( model, options ) { |
|
792 // Allow 'model' to set up its relations before proceeding. |
|
793 // (which can result in a call to 'addRelated' from a relation of 'model') |
|
794 var dit = this; |
|
795 model.queue( function() { |
|
796 if ( model !== dit.related ) { |
|
797 var oldRelated = dit.related || null; |
|
798 dit.setRelated( model ); |
|
799 dit.onChange( dit.instance, model, _.defaults( { __related: oldRelated }, options ) ); |
|
800 } |
|
801 }); |
|
802 }, |
|
803 |
|
804 removeRelated: function( model, coll, options ) { |
|
805 if ( !this.related ) { |
|
806 return; |
|
807 } |
|
808 |
|
809 if ( model === this.related ) { |
|
810 var oldRelated = this.related || null; |
|
811 this.setRelated( null ); |
|
812 this.onChange( this.instance, model, _.defaults( { __related: oldRelated }, options ) ); |
|
813 } |
|
814 } |
|
815 }); |
|
816 |
|
817 Backbone.HasMany = Backbone.Relation.extend({ |
|
818 collectionType: null, |
|
819 |
|
820 options: { |
|
821 reverseRelation: { type: 'HasOne' }, |
|
822 collectionType: Backbone.Collection, |
|
823 collectionKey: true, |
|
824 collectionOptions: {} |
|
825 }, |
|
826 |
|
827 initialize: function( opts ) { |
|
828 this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange ); |
|
829 |
|
830 // Handle a custom 'collectionType' |
|
831 this.collectionType = this.options.collectionType; |
|
832 if ( _.isString( this.collectionType ) ) { |
|
833 this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType ); |
|
834 } |
|
835 if ( this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) { |
|
836 throw new Error( '`collectionType` must inherit from Backbone.Collection' ); |
|
837 } |
|
838 |
|
839 var related = this.findRelated( opts ); |
|
840 this.setRelated( related ); |
|
841 }, |
|
842 |
|
843 /** |
|
844 * Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany. |
|
845 * If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option. |
|
846 * @param {Backbone.Collection} [collection] |
|
847 * @return {Backbone.Collection} |
|
848 */ |
|
849 _prepareCollection: function( collection ) { |
|
850 if ( this.related ) { |
|
851 this.stopListening( this.related ); |
|
852 } |
|
853 |
|
854 if ( !collection || !( collection instanceof Backbone.Collection ) ) { |
|
855 var options = _.isFunction( this.options.collectionOptions ) ? |
|
856 this.options.collectionOptions( this.instance ) : this.options.collectionOptions; |
|
857 |
|
858 collection = new this.collectionType( null, options ); |
|
859 } |
|
860 |
|
861 collection.model = this.relatedModel; |
|
862 |
|
863 if ( this.options.collectionKey ) { |
|
864 var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; |
|
865 |
|
866 if ( collection[ key ] && collection[ key ] !== this.instance ) { |
|
867 if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { |
|
868 console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); |
|
869 } |
|
870 } |
|
871 else if ( key ) { |
|
872 collection[ key ] = this.instance; |
|
873 } |
|
874 } |
|
875 |
|
876 this.listenTo( collection, 'relational:add', this.handleAddition ) |
|
877 .listenTo( collection, 'relational:remove', this.handleRemoval ) |
|
878 .listenTo( collection, 'relational:reset', this.handleReset ); |
|
879 |
|
880 return collection; |
|
881 }, |
|
882 |
|
883 /** |
|
884 * Find related Models. |
|
885 * @param {Object} [options] |
|
886 * @return {Backbone.Collection} |
|
887 */ |
|
888 findRelated: function( options ) { |
|
889 var related = null; |
|
890 |
|
891 options = _.defaults( { parse: this.options.parse }, options ); |
|
892 |
|
893 // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection |
|
894 if ( this.keyContents instanceof Backbone.Collection ) { |
|
895 this._prepareCollection( this.keyContents ); |
|
896 related = this.keyContents; |
|
897 } |
|
898 // Otherwise, 'this.keyContents' should be an array of related object ids. |
|
899 // Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection. |
|
900 else { |
|
901 var toAdd = []; |
|
902 |
|
903 _.each( this.keyContents, function( attributes ) { |
|
904 if ( attributes instanceof this.relatedModel ) { |
|
905 var model = attributes; |
|
906 } |
|
907 else { |
|
908 // If `merge` is true, update models here, instead of during update. |
|
909 model = this.relatedModel.findOrCreate( attributes, |
|
910 _.extend( { merge: true }, options, { create: this.options.createModels } ) |
|
911 ); |
|
912 } |
|
913 |
|
914 model && toAdd.push( model ); |
|
915 }, this ); |
|
916 |
|
917 if ( this.related instanceof Backbone.Collection ) { |
|
918 related = this.related; |
|
919 } |
|
920 else { |
|
921 related = this._prepareCollection(); |
|
922 } |
|
923 |
|
924 // By now, both `merge` and `parse` will already have been executed for models if they were specified. |
|
925 // Disable them to prevent additional calls. |
|
926 related.set( toAdd, _.defaults( { merge: false, parse: false }, options ) ); |
|
927 } |
|
928 |
|
929 // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged') |
|
930 this.keyIds = _.difference( this.keyIds, _.pluck( related.models, 'id' ) ); |
|
931 |
|
932 return related; |
|
933 }, |
|
934 |
|
935 /** |
|
936 * Normalize and reduce `keyContents` to a list of `ids`, for easier comparison |
|
937 * @param {String|Number|String[]|Number[]|Backbone.Collection} keyContents |
|
938 */ |
|
939 setKeyContents: function( keyContents ) { |
|
940 this.keyContents = keyContents instanceof Backbone.Collection ? keyContents : null; |
|
941 this.keyIds = []; |
|
942 |
|
943 if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well |
|
944 // Handle cases the an API/user supplies just an Object/id instead of an Array |
|
945 this.keyContents = _.isArray( keyContents ) ? keyContents : [ keyContents ]; |
|
946 |
|
947 _.each( this.keyContents, function( item ) { |
|
948 var itemId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); |
|
949 if ( itemId || itemId === 0 ) { |
|
950 this.keyIds.push( itemId ); |
|
951 } |
|
952 }, this ); |
|
953 } |
|
954 }, |
|
955 |
|
956 /** |
|
957 * Event handler for `change:<key>`. |
|
958 * If the contents of the key are changed, notify old & new reverse relations and initialize the new relation. |
|
959 */ |
|
960 onChange: function( model, attr, options ) { |
|
961 options = options ? _.clone( options ) : {}; |
|
962 this.setKeyContents( attr ); |
|
963 this.changed = false; |
|
964 |
|
965 var related = this.findRelated( options ); |
|
966 this.setRelated( related ); |
|
967 |
|
968 if ( !options.silent ) { |
|
969 var dit = this; |
|
970 Backbone.Relational.eventQueue.add( function() { |
|
971 // The `changed` flag can be set in `handleAddition` or `handleRemoval` |
|
972 if ( dit.changed ) { |
|
973 dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true ); |
|
974 dit.changed = false; |
|
975 } |
|
976 }); |
|
977 } |
|
978 }, |
|
979 |
|
980 /** |
|
981 * When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations. |
|
982 * (should be 'HasOne', must set 'this.instance' as their related). |
|
983 */ |
|
984 handleAddition: function( model, coll, options ) { |
|
985 //console.debug('handleAddition called; args=%o', arguments); |
|
986 options = options ? _.clone( options ) : {}; |
|
987 this.changed = true; |
|
988 |
|
989 _.each( this.getReverseRelations( model ), function( relation ) { |
|
990 relation.addRelated( this.instance, options ); |
|
991 }, this ); |
|
992 |
|
993 // Only trigger 'add' once the newly added model is initialized (so, has its relations set up) |
|
994 var dit = this; |
|
995 !options.silent && Backbone.Relational.eventQueue.add( function() { |
|
996 dit.instance.trigger( 'add:' + dit.key, model, dit.related, options ); |
|
997 }); |
|
998 }, |
|
999 |
|
1000 /** |
|
1001 * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations. |
|
1002 * (should be 'HasOne', which should be nullified) |
|
1003 */ |
|
1004 handleRemoval: function( model, coll, options ) { |
|
1005 //console.debug('handleRemoval called; args=%o', arguments); |
|
1006 options = options ? _.clone( options ) : {}; |
|
1007 this.changed = true; |
|
1008 |
|
1009 _.each( this.getReverseRelations( model ), function( relation ) { |
|
1010 relation.removeRelated( this.instance, null, options ); |
|
1011 }, this ); |
|
1012 |
|
1013 var dit = this; |
|
1014 !options.silent && Backbone.Relational.eventQueue.add( function() { |
|
1015 dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options ); |
|
1016 }); |
|
1017 }, |
|
1018 |
|
1019 handleReset: function( coll, options ) { |
|
1020 var dit = this; |
|
1021 options = options ? _.clone( options ) : {}; |
|
1022 !options.silent && Backbone.Relational.eventQueue.add( function() { |
|
1023 dit.instance.trigger( 'reset:' + dit.key, dit.related, options ); |
|
1024 }); |
|
1025 }, |
|
1026 |
|
1027 tryAddRelated: function( model, coll, options ) { |
|
1028 var item = _.contains( this.keyIds, model.id ); |
|
1029 |
|
1030 if ( item ) { |
|
1031 this.addRelated( model, options ); |
|
1032 this.keyIds = _.without( this.keyIds, model.id ); |
|
1033 } |
|
1034 }, |
|
1035 |
|
1036 addRelated: function( model, options ) { |
|
1037 // Allow 'model' to set up its relations before proceeding. |
|
1038 // (which can result in a call to 'addRelated' from a relation of 'model') |
|
1039 var dit = this; |
|
1040 model.queue( function() { |
|
1041 if ( dit.related && !dit.related.get( model ) ) { |
|
1042 dit.related.add( model, _.defaults( { parse: false }, options ) ); |
|
1043 } |
|
1044 }); |
|
1045 }, |
|
1046 |
|
1047 removeRelated: function( model, coll, options ) { |
|
1048 if ( this.related.get( model ) ) { |
|
1049 this.related.remove( model, options ); |
|
1050 } |
|
1051 } |
|
1052 }); |
|
1053 |
|
1054 /** |
|
1055 * A type of Backbone.Model that also maintains relations to other models and collections. |
|
1056 * New events when compared to the original: |
|
1057 * - 'add:<key>' (model, related collection, options) |
|
1058 * - 'remove:<key>' (model, related collection, options) |
|
1059 * - 'change:<key>' (model, related model or collection, options) |
|
1060 */ |
|
1061 Backbone.RelationalModel = Backbone.Model.extend({ |
|
1062 relations: null, // Relation descriptions on the prototype |
|
1063 _relations: null, // Relation instances |
|
1064 _isInitialized: false, |
|
1065 _deferProcessing: false, |
|
1066 _queue: null, |
|
1067 |
|
1068 subModelTypeAttribute: 'type', |
|
1069 subModelTypes: null, |
|
1070 |
|
1071 constructor: function( attributes, options ) { |
|
1072 // Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'. |
|
1073 // Defer 'processQueue', so that when 'Relation.createModels' is used we trigger 'HasMany' |
|
1074 // collection events only after the model is really fully set up. |
|
1075 // Example: event for "p.on( 'add:jobs' )" -> "p.get('jobs').add( { company: c.id, person: p.id } )". |
|
1076 if ( options && options.collection ) { |
|
1077 var dit = this, |
|
1078 collection = this.collection = options.collection; |
|
1079 |
|
1080 // Prevent `collection` from cascading down to nested models; they shouldn't go into this `if` clause. |
|
1081 delete options.collection; |
|
1082 |
|
1083 this._deferProcessing = true; |
|
1084 |
|
1085 var processQueue = function( model ) { |
|
1086 if ( model === dit ) { |
|
1087 dit._deferProcessing = false; |
|
1088 dit.processQueue(); |
|
1089 collection.off( 'relational:add', processQueue ); |
|
1090 } |
|
1091 }; |
|
1092 collection.on( 'relational:add', processQueue ); |
|
1093 |
|
1094 // So we do process the queue eventually, regardless of whether this model actually gets added to 'options.collection'. |
|
1095 _.defer( function() { |
|
1096 processQueue( dit ); |
|
1097 }); |
|
1098 } |
|
1099 |
|
1100 Backbone.Relational.store.processOrphanRelations(); |
|
1101 |
|
1102 this._queue = new Backbone.BlockingQueue(); |
|
1103 this._queue.block(); |
|
1104 Backbone.Relational.eventQueue.block(); |
|
1105 |
|
1106 try { |
|
1107 Backbone.Model.apply( this, arguments ); |
|
1108 } |
|
1109 finally { |
|
1110 // Try to run the global queue holding external events |
|
1111 Backbone.Relational.eventQueue.unblock(); |
|
1112 } |
|
1113 }, |
|
1114 |
|
1115 /** |
|
1116 * Override 'trigger' to queue 'change' and 'change:*' events |
|
1117 */ |
|
1118 trigger: function( eventName ) { |
|
1119 if ( eventName.length > 5 && eventName.indexOf( 'change' ) === 0 ) { |
|
1120 var dit = this, |
|
1121 args = arguments; |
|
1122 |
|
1123 Backbone.Relational.eventQueue.add( function() { |
|
1124 if ( !dit._isInitialized ) { |
|
1125 return; |
|
1126 } |
|
1127 |
|
1128 // Determine if the `change` event is still valid, now that all relations are populated |
|
1129 var changed = true; |
|
1130 if ( eventName === 'change' ) { |
|
1131 changed = dit.hasChanged(); |
|
1132 } |
|
1133 else { |
|
1134 var attr = eventName.slice( 7 ), |
|
1135 rel = dit.getRelation( attr ); |
|
1136 |
|
1137 if ( rel ) { |
|
1138 // If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`. |
|
1139 // These take precedence over `change:attr` events triggered by `Model.set`. |
|
1140 // The relation set a fourth attribute to `true`. If this attribute is present, |
|
1141 // continue triggering this event; otherwise, it's from `Model.set` and should be stopped. |
|
1142 changed = ( args[ 4 ] === true ); |
|
1143 |
|
1144 // If this event was triggered by a relation, set the right value in `this.changed` |
|
1145 // (a Collection or Model instead of raw data). |
|
1146 if ( changed ) { |
|
1147 dit.changed[ attr ] = args[ 2 ]; |
|
1148 } |
|
1149 // Otherwise, this event is from `Model.set`. If the relation doesn't report a change, |
|
1150 // remove attr from `dit.changed` so `hasChanged` doesn't take it into account. |
|
1151 else if ( !rel.changed ) { |
|
1152 delete dit.changed[ attr ]; |
|
1153 } |
|
1154 } |
|
1155 } |
|
1156 |
|
1157 changed && Backbone.Model.prototype.trigger.apply( dit, args ); |
|
1158 }); |
|
1159 } |
|
1160 else { |
|
1161 Backbone.Model.prototype.trigger.apply( this, arguments ); |
|
1162 } |
|
1163 |
|
1164 return this; |
|
1165 }, |
|
1166 |
|
1167 /** |
|
1168 * Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance. |
|
1169 * Invoked in the first call so 'set' (which is made from the Backbone.Model constructor). |
|
1170 */ |
|
1171 initializeRelations: function( options ) { |
|
1172 this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once |
|
1173 this._relations = {}; |
|
1174 |
|
1175 _.each( this.relations || [], function( rel ) { |
|
1176 Backbone.Relational.store.initializeRelation( this, rel, options ); |
|
1177 }, this ); |
|
1178 |
|
1179 this._isInitialized = true; |
|
1180 this.release(); |
|
1181 this.processQueue(); |
|
1182 }, |
|
1183 |
|
1184 /** |
|
1185 * When new values are set, notify this model's relations (also if options.silent is set). |
|
1186 * (Relation.setRelated locks this model before calling 'set' on it to prevent loops) |
|
1187 */ |
|
1188 updateRelations: function( options ) { |
|
1189 if ( this._isInitialized && !this.isLocked() ) { |
|
1190 _.each( this._relations, function( rel ) { |
|
1191 // Update from data in `rel.keySource` if set, or `rel.key` otherwise |
|
1192 var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ]; |
|
1193 if ( rel.related !== val ) { |
|
1194 this.trigger( 'relational:change:' + rel.key, this, val, options || {} ); |
|
1195 } |
|
1196 }, this ); |
|
1197 } |
|
1198 }, |
|
1199 |
|
1200 /** |
|
1201 * Either add to the queue (if we're not initialized yet), or execute right away. |
|
1202 */ |
|
1203 queue: function( func ) { |
|
1204 this._queue.add( func ); |
|
1205 }, |
|
1206 |
|
1207 /** |
|
1208 * Process _queue |
|
1209 */ |
|
1210 processQueue: function() { |
|
1211 if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) { |
|
1212 this._queue.unblock(); |
|
1213 } |
|
1214 }, |
|
1215 |
|
1216 /** |
|
1217 * Get a specific relation. |
|
1218 * @param key {string} The relation key to look for. |
|
1219 * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'key', or null. |
|
1220 */ |
|
1221 getRelation: function( key ) { |
|
1222 return this._relations[ key ]; |
|
1223 }, |
|
1224 |
|
1225 /** |
|
1226 * Get all of the created relations. |
|
1227 * @return {Backbone.Relation[]} |
|
1228 */ |
|
1229 getRelations: function() { |
|
1230 return _.values( this._relations ); |
|
1231 }, |
|
1232 |
|
1233 /** |
|
1234 * Retrieve related objects. |
|
1235 * @param key {string} The relation key to fetch models for. |
|
1236 * @param [options] {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'. |
|
1237 * @param [refresh=false] {boolean} Fetch existing models from the server as well (in order to update them). |
|
1238 * @return {jQuery.when[]} An array of request objects |
|
1239 */ |
|
1240 fetchRelated: function( key, options, refresh ) { |
|
1241 // Set default `options` for fetch |
|
1242 options = _.extend( { update: true, remove: false }, options ); |
|
1243 |
|
1244 var setUrl, |
|
1245 requests = [], |
|
1246 rel = this.getRelation( key ), |
|
1247 idsToFetch = rel && ( rel.keyIds || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) ); |
|
1248 |
|
1249 // On `refresh`, add the ids for current models in the relation to `idsToFetch` |
|
1250 if ( refresh ) { |
|
1251 var models = rel.related instanceof Backbone.Collection ? rel.related.models : [ rel.related ]; |
|
1252 _.each( models, function( model ) { |
|
1253 if ( model.id || model.id === 0 ) { |
|
1254 idsToFetch.push( model.id ); |
|
1255 } |
|
1256 }); |
|
1257 } |
|
1258 |
|
1259 if ( idsToFetch && idsToFetch.length ) { |
|
1260 // Find (or create) a model for each one that is to be fetched |
|
1261 var created = [], |
|
1262 models = _.map( idsToFetch, function( id ) { |
|
1263 var model = Backbone.Relational.store.find( rel.relatedModel, id ); |
|
1264 |
|
1265 if ( !model ) { |
|
1266 var attrs = {}; |
|
1267 attrs[ rel.relatedModel.prototype.idAttribute ] = id; |
|
1268 model = rel.relatedModel.findOrCreate( attrs, options ); |
|
1269 created.push( model ); |
|
1270 } |
|
1271 |
|
1272 return model; |
|
1273 }, this ); |
|
1274 |
|
1275 // Try if the 'collection' can provide a url to fetch a set of models in one request. |
|
1276 if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) { |
|
1277 setUrl = rel.related.url( models ); |
|
1278 } |
|
1279 |
|
1280 // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. |
|
1281 // To make sure it can, test if the url we got by supplying a list of models to fetch is different from |
|
1282 // the one supplied for the default fetch action (without args to 'url'). |
|
1283 if ( setUrl && setUrl !== rel.related.url() ) { |
|
1284 var opts = _.defaults( |
|
1285 { |
|
1286 error: function() { |
|
1287 var args = arguments; |
|
1288 _.each( created, function( model ) { |
|
1289 model.trigger( 'destroy', model, model.collection, options ); |
|
1290 options.error && options.error.apply( model, args ); |
|
1291 }); |
|
1292 }, |
|
1293 url: setUrl |
|
1294 }, |
|
1295 options |
|
1296 ); |
|
1297 |
|
1298 requests = [ rel.related.fetch( opts ) ]; |
|
1299 } |
|
1300 else { |
|
1301 requests = _.map( models, function( model ) { |
|
1302 var opts = _.defaults( |
|
1303 { |
|
1304 error: function() { |
|
1305 if ( _.contains( created, model ) ) { |
|
1306 model.trigger( 'destroy', model, model.collection, options ); |
|
1307 options.error && options.error.apply( model, arguments ); |
|
1308 } |
|
1309 } |
|
1310 }, |
|
1311 options |
|
1312 ); |
|
1313 return model.fetch( opts ); |
|
1314 }, this ); |
|
1315 } |
|
1316 } |
|
1317 |
|
1318 return requests; |
|
1319 }, |
|
1320 |
|
1321 get: function( attr ) { |
|
1322 var originalResult = Backbone.Model.prototype.get.call( this, attr ); |
|
1323 |
|
1324 // Use `originalResult` get if dotNotation not enabled or not required because no dot is in `attr` |
|
1325 if ( !this.dotNotation || attr.indexOf( '.' ) === -1 ) { |
|
1326 return originalResult; |
|
1327 } |
|
1328 |
|
1329 // Go through all splits and return the final result |
|
1330 var splits = attr.split( '.' ); |
|
1331 var result = _.reduce(splits, function( model, split ) { |
|
1332 if ( !( model instanceof Backbone.Model ) ) { |
|
1333 throw new Error( 'Attribute must be an instanceof Backbone.Model. Is: ' + model + ', currentSplit: ' + split ); |
|
1334 } |
|
1335 |
|
1336 return Backbone.Model.prototype.get.call( model, split ); |
|
1337 }, this ); |
|
1338 |
|
1339 if ( originalResult !== undefined && result !== undefined ) { |
|
1340 throw new Error( "Ambiguous result for '" + attr + "'. direct result: " + originalResult + ", dotNotation: " + result ); |
|
1341 } |
|
1342 |
|
1343 return originalResult || result; |
|
1344 }, |
|
1345 |
|
1346 set: function( key, value, options ) { |
|
1347 Backbone.Relational.eventQueue.block(); |
|
1348 |
|
1349 // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object |
|
1350 var attributes; |
|
1351 if ( _.isObject( key ) || key == null ) { |
|
1352 attributes = key; |
|
1353 options = value; |
|
1354 } |
|
1355 else { |
|
1356 attributes = {}; |
|
1357 attributes[ key ] = value; |
|
1358 } |
|
1359 |
|
1360 try { |
|
1361 var id = this.id, |
|
1362 newId = attributes && this.idAttribute in attributes && attributes[ this.idAttribute ]; |
|
1363 |
|
1364 // Check if we're not setting a duplicate id before actually calling `set`. |
|
1365 Backbone.Relational.store.checkId( this, newId ); |
|
1366 |
|
1367 var result = Backbone.Model.prototype.set.apply( this, arguments ); |
|
1368 |
|
1369 // Ideal place to set up relations, if this is the first time we're here for this model |
|
1370 if ( !this._isInitialized && !this.isLocked() ) { |
|
1371 this.constructor.initializeModelHierarchy(); |
|
1372 Backbone.Relational.store.register( this ); |
|
1373 this.initializeRelations( options ); |
|
1374 } |
|
1375 // The store should know about an `id` update asap |
|
1376 else if ( newId && newId !== id ) { |
|
1377 Backbone.Relational.store.update( this ); |
|
1378 } |
|
1379 |
|
1380 if ( attributes ) { |
|
1381 this.updateRelations( options ); |
|
1382 } |
|
1383 } |
|
1384 finally { |
|
1385 // Try to run the global queue holding external events |
|
1386 Backbone.Relational.eventQueue.unblock(); |
|
1387 } |
|
1388 |
|
1389 return result; |
|
1390 }, |
|
1391 |
|
1392 unset: function( attribute, options ) { |
|
1393 Backbone.Relational.eventQueue.block(); |
|
1394 |
|
1395 var result = Backbone.Model.prototype.unset.apply( this, arguments ); |
|
1396 this.updateRelations( options ); |
|
1397 |
|
1398 // Try to run the global queue holding external events |
|
1399 Backbone.Relational.eventQueue.unblock(); |
|
1400 |
|
1401 return result; |
|
1402 }, |
|
1403 |
|
1404 clear: function( options ) { |
|
1405 Backbone.Relational.eventQueue.block(); |
|
1406 |
|
1407 var result = Backbone.Model.prototype.clear.apply( this, arguments ); |
|
1408 this.updateRelations( options ); |
|
1409 |
|
1410 // Try to run the global queue holding external events |
|
1411 Backbone.Relational.eventQueue.unblock(); |
|
1412 |
|
1413 return result; |
|
1414 }, |
|
1415 |
|
1416 clone: function() { |
|
1417 var attributes = _.clone( this.attributes ); |
|
1418 if ( !_.isUndefined( attributes[ this.idAttribute ] ) ) { |
|
1419 attributes[ this.idAttribute ] = null; |
|
1420 } |
|
1421 |
|
1422 _.each( this.getRelations(), function( rel ) { |
|
1423 delete attributes[ rel.key ]; |
|
1424 }); |
|
1425 |
|
1426 return new this.constructor( attributes ); |
|
1427 }, |
|
1428 |
|
1429 /** |
|
1430 * Convert relations to JSON, omits them when required |
|
1431 */ |
|
1432 toJSON: function( options ) { |
|
1433 // If this Model has already been fully serialized in this branch once, return to avoid loops |
|
1434 if ( this.isLocked() ) { |
|
1435 return this.id; |
|
1436 } |
|
1437 |
|
1438 this.acquire(); |
|
1439 var json = Backbone.Model.prototype.toJSON.call( this, options ); |
|
1440 |
|
1441 if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) { |
|
1442 json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue; |
|
1443 } |
|
1444 |
|
1445 _.each( this._relations, function( rel ) { |
|
1446 var related = json[ rel.key ], |
|
1447 includeInJSON = rel.options.includeInJSON, |
|
1448 value = null; |
|
1449 |
|
1450 if ( includeInJSON === true ) { |
|
1451 if ( related && _.isFunction( related.toJSON ) ) { |
|
1452 value = related.toJSON( options ); |
|
1453 } |
|
1454 } |
|
1455 else if ( _.isString( includeInJSON ) ) { |
|
1456 if ( related instanceof Backbone.Collection ) { |
|
1457 value = related.pluck( includeInJSON ); |
|
1458 } |
|
1459 else if ( related instanceof Backbone.Model ) { |
|
1460 value = related.get( includeInJSON ); |
|
1461 } |
|
1462 |
|
1463 // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute` |
|
1464 if ( includeInJSON === rel.relatedModel.prototype.idAttribute ) { |
|
1465 if ( rel instanceof Backbone.HasMany ) { |
|
1466 value = value.concat( rel.keyIds ); |
|
1467 } |
|
1468 else if ( rel instanceof Backbone.HasOne ) { |
|
1469 value = value || rel.keyId; |
|
1470 } |
|
1471 } |
|
1472 } |
|
1473 else if ( _.isArray( includeInJSON ) ) { |
|
1474 if ( related instanceof Backbone.Collection ) { |
|
1475 value = []; |
|
1476 related.each( function( model ) { |
|
1477 var curJson = {}; |
|
1478 _.each( includeInJSON, function( key ) { |
|
1479 curJson[ key ] = model.get( key ); |
|
1480 }); |
|
1481 value.push( curJson ); |
|
1482 }); |
|
1483 } |
|
1484 else if ( related instanceof Backbone.Model ) { |
|
1485 value = {}; |
|
1486 _.each( includeInJSON, function( key ) { |
|
1487 value[ key ] = related.get( key ); |
|
1488 }); |
|
1489 } |
|
1490 } |
|
1491 else { |
|
1492 delete json[ rel.key ]; |
|
1493 } |
|
1494 |
|
1495 if ( includeInJSON ) { |
|
1496 json[ rel.keyDestination ] = value; |
|
1497 } |
|
1498 |
|
1499 if ( rel.keyDestination !== rel.key ) { |
|
1500 delete json[ rel.key ]; |
|
1501 } |
|
1502 }); |
|
1503 |
|
1504 this.release(); |
|
1505 return json; |
|
1506 } |
|
1507 }, |
|
1508 { |
|
1509 /** |
|
1510 * |
|
1511 * @param superModel |
|
1512 * @returns {Backbone.RelationalModel.constructor} |
|
1513 */ |
|
1514 setup: function( superModel ) { |
|
1515 // We don't want to share a relations array with a parent, as this will cause problems with |
|
1516 // reverse relations. |
|
1517 this.prototype.relations = ( this.prototype.relations || [] ).slice( 0 ); |
|
1518 |
|
1519 this._subModels = {}; |
|
1520 this._superModel = null; |
|
1521 |
|
1522 // If this model has 'subModelTypes' itself, remember them in the store |
|
1523 if ( this.prototype.hasOwnProperty( 'subModelTypes' ) ) { |
|
1524 Backbone.Relational.store.addSubModels( this.prototype.subModelTypes, this ); |
|
1525 } |
|
1526 // The 'subModelTypes' property should not be inherited, so reset it. |
|
1527 else { |
|
1528 this.prototype.subModelTypes = null; |
|
1529 } |
|
1530 |
|
1531 // Initialize all reverseRelations that belong to this new model. |
|
1532 _.each( this.prototype.relations || [], function( rel ) { |
|
1533 if ( !rel.model ) { |
|
1534 rel.model = this; |
|
1535 } |
|
1536 |
|
1537 if ( rel.reverseRelation && rel.model === this ) { |
|
1538 var preInitialize = true; |
|
1539 if ( _.isString( rel.relatedModel ) ) { |
|
1540 /** |
|
1541 * The related model might not be defined for two reasons |
|
1542 * 1. it is related to itself |
|
1543 * 2. it never gets defined, e.g. a typo |
|
1544 * 3. the model hasn't been defined yet, but will be later |
|
1545 * In neither of these cases do we need to pre-initialize reverse relations. |
|
1546 * However, for 3. (which is, to us, indistinguishable from 2.), we do need to attempt |
|
1547 * setting up this relation again later, in case the related model is defined later. |
|
1548 */ |
|
1549 var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); |
|
1550 preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel ); |
|
1551 } |
|
1552 |
|
1553 if ( preInitialize ) { |
|
1554 Backbone.Relational.store.initializeRelation( null, rel ); |
|
1555 } |
|
1556 else if ( _.isString( rel.relatedModel ) ) { |
|
1557 Backbone.Relational.store.addOrphanRelation( rel ); |
|
1558 } |
|
1559 } |
|
1560 }, this ); |
|
1561 |
|
1562 return this; |
|
1563 }, |
|
1564 |
|
1565 /** |
|
1566 * Create a 'Backbone.Model' instance based on 'attributes'. |
|
1567 * @param {Object} attributes |
|
1568 * @param {Object} [options] |
|
1569 * @return {Backbone.Model} |
|
1570 */ |
|
1571 build: function( attributes, options ) { |
|
1572 var model = this; |
|
1573 |
|
1574 // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet. |
|
1575 this.initializeModelHierarchy(); |
|
1576 |
|
1577 // Determine what type of (sub)model should be built if applicable. |
|
1578 // Lookup the proper subModelType in 'this._subModels'. |
|
1579 if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) { |
|
1580 var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ]; |
|
1581 var subModelType = this._subModels[ subModelTypeAttribute ]; |
|
1582 if ( subModelType ) { |
|
1583 model = subModelType; |
|
1584 } |
|
1585 } |
|
1586 |
|
1587 return new model( attributes, options ); |
|
1588 }, |
|
1589 |
|
1590 /** |
|
1591 * |
|
1592 */ |
|
1593 initializeModelHierarchy: function() { |
|
1594 // If we're here for the first time, try to determine if this modelType has a 'superModel'. |
|
1595 if ( _.isUndefined( this._superModel ) || _.isNull( this._superModel ) ) { |
|
1596 Backbone.Relational.store.setupSuperModel( this ); |
|
1597 |
|
1598 // If a superModel has been found, copy relations from the _superModel if they haven't been |
|
1599 // inherited automatically (due to a redefinition of 'relations'). |
|
1600 // Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail |
|
1601 // the isUndefined/isNull check next time. |
|
1602 if ( this._superModel && this._superModel.prototype.relations ) { |
|
1603 // Find relations that exist on the `_superModel`, but not yet on this model. |
|
1604 var inheritedRelations = _.select( this._superModel.prototype.relations || [], function( superRel ) { |
|
1605 return !_.any( this.prototype.relations || [], function( rel ) { |
|
1606 return superRel.relatedModel === rel.relatedModel && superRel.key === rel.key; |
|
1607 }, this ); |
|
1608 }, this ); |
|
1609 |
|
1610 this.prototype.relations = inheritedRelations.concat( this.prototype.relations ); |
|
1611 } |
|
1612 else { |
|
1613 this._superModel = false; |
|
1614 } |
|
1615 } |
|
1616 |
|
1617 // If we came here through 'build' for a model that has 'subModelTypes', and not all of them have been resolved yet, try to resolve each. |
|
1618 if ( this.prototype.subModelTypes && _.keys( this.prototype.subModelTypes ).length !== _.keys( this._subModels ).length ) { |
|
1619 _.each( this.prototype.subModelTypes || [], function( subModelTypeName ) { |
|
1620 var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName ); |
|
1621 subModelType && subModelType.initializeModelHierarchy(); |
|
1622 }); |
|
1623 } |
|
1624 }, |
|
1625 |
|
1626 /** |
|
1627 * Find an instance of `this` type in 'Backbone.Relational.store'. |
|
1628 * - If `attributes` is a string or a number, `findOrCreate` will just query the `store` and return a model if found. |
|
1629 * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.update` is `false`. |
|
1630 * Otherwise, a new model is created with `attributes` (unless `options.create` is explicitly set to `false`). |
|
1631 * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model. |
|
1632 * @param {Object} [options] |
|
1633 * @param {Boolean} [options.create=true] |
|
1634 * @param {Boolean} [options.merge=true] |
|
1635 * @param {Boolean} [options.parse=false] |
|
1636 * @return {Backbone.RelationalModel} |
|
1637 */ |
|
1638 findOrCreate: function( attributes, options ) { |
|
1639 options || ( options = {} ); |
|
1640 var parsedAttributes = ( _.isObject( attributes ) && options.parse && this.prototype.parse ) ? |
|
1641 this.prototype.parse( attributes ) : attributes; |
|
1642 |
|
1643 // Try to find an instance of 'this' model type in the store |
|
1644 var model = Backbone.Relational.store.find( this, parsedAttributes ); |
|
1645 |
|
1646 // If we found an instance, update it with the data in 'item' (unless 'options.merge' is false). |
|
1647 // If not, create an instance (unless 'options.create' is false). |
|
1648 if ( _.isObject( attributes ) ) { |
|
1649 if ( model && options.merge !== false ) { |
|
1650 // Make sure `options.collection` doesn't cascade to nested models |
|
1651 delete options.collection; |
|
1652 |
|
1653 model.set( parsedAttributes, options ); |
|
1654 } |
|
1655 else if ( !model && options.create !== false ) { |
|
1656 model = this.build( attributes, options ); |
|
1657 } |
|
1658 } |
|
1659 |
|
1660 return model; |
|
1661 } |
|
1662 }); |
|
1663 _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore ); |
|
1664 |
|
1665 /** |
|
1666 * Override Backbone.Collection._prepareModel, so objects will be built using the correct type |
|
1667 * if the collection.model has subModels. |
|
1668 * Attempts to find a model for `attrs` in Backbone.store through `findOrCreate` |
|
1669 * (which sets the new properties on it if found), or instantiates a new model. |
|
1670 */ |
|
1671 Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel; |
|
1672 Backbone.Collection.prototype._prepareModel = function ( attrs, options ) { |
|
1673 var model; |
|
1674 |
|
1675 if ( attrs instanceof Backbone.Model ) { |
|
1676 if ( !attrs.collection ) { |
|
1677 attrs.collection = this; |
|
1678 } |
|
1679 model = attrs; |
|
1680 } |
|
1681 else { |
|
1682 options || ( options = {} ); |
|
1683 options.collection = this; |
|
1684 |
|
1685 if ( typeof this.model.findOrCreate !== 'undefined' ) { |
|
1686 model = this.model.findOrCreate( attrs, options ); |
|
1687 } |
|
1688 else { |
|
1689 model = new this.model( attrs, options ); |
|
1690 } |
|
1691 |
|
1692 if ( model && model.isNew() && !model._validate( attrs, options ) ) { |
|
1693 this.trigger( 'invalid', this, attrs, options ); |
|
1694 model = false; |
|
1695 } |
|
1696 } |
|
1697 |
|
1698 return model; |
|
1699 }; |
|
1700 |
|
1701 |
|
1702 /** |
|
1703 * Override Backbone.Collection.set, so we'll create objects from attributes where required, |
|
1704 * and update the existing models. Also, trigger 'relational:add'. |
|
1705 */ |
|
1706 var set = Backbone.Collection.prototype.__set = Backbone.Collection.prototype.set; |
|
1707 Backbone.Collection.prototype.set = function( models, options ) { |
|
1708 // Short-circuit if this Collection doesn't hold RelationalModels |
|
1709 if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { |
|
1710 return set.apply( this, arguments ); |
|
1711 } |
|
1712 |
|
1713 if ( options && options.parse ) { |
|
1714 models = this.parse( models, options ); |
|
1715 } |
|
1716 |
|
1717 if ( !_.isArray( models ) ) { |
|
1718 models = models ? [ models ] : []; |
|
1719 } |
|
1720 |
|
1721 var newModels = [], |
|
1722 toAdd = []; |
|
1723 |
|
1724 //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options ); |
|
1725 _.each( models, function( model ) { |
|
1726 if ( !( model instanceof Backbone.Model ) ) { |
|
1727 model = Backbone.Collection.prototype._prepareModel.call( this, model, options ); |
|
1728 } |
|
1729 |
|
1730 if ( model ) { |
|
1731 toAdd.push( model ); |
|
1732 |
|
1733 if ( !( this.get( model ) || this.get( model.cid ) ) ) { |
|
1734 newModels.push( model ); |
|
1735 } |
|
1736 // If we arrive in `add` while performing a `set` (after a create, so the model gains an `id`), |
|
1737 // we may get here before `_onModelEvent` has had the chance to update `_byId`. |
|
1738 else if ( model.id != null ) { |
|
1739 this._byId[ model.id ] = model; |
|
1740 } |
|
1741 } |
|
1742 }, this ); |
|
1743 |
|
1744 // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc). |
|
1745 // If `parse` was specified, the collection and contained models have been parsed now. |
|
1746 set.call( this, toAdd, _.defaults( { parse: false }, options ) ); |
|
1747 |
|
1748 _.each( newModels, function( model ) { |
|
1749 // Fire a `relational:add` event for any model in `newModels` that has actually been added to the collection. |
|
1750 if ( this.get( model ) || this.get( model.cid ) ) { |
|
1751 this.trigger( 'relational:add', model, this, options ); |
|
1752 } |
|
1753 }, this ); |
|
1754 |
|
1755 return this; |
|
1756 }; |
|
1757 |
|
1758 /** |
|
1759 * Override 'Backbone.Collection.remove' to trigger 'relational:remove'. |
|
1760 */ |
|
1761 var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove; |
|
1762 Backbone.Collection.prototype.remove = function( models, options ) { |
|
1763 // Short-circuit if this Collection doesn't hold RelationalModels |
|
1764 if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { |
|
1765 return remove.apply( this, arguments ); |
|
1766 } |
|
1767 |
|
1768 models = _.isArray( models ) ? models.slice() : [ models ]; |
|
1769 options || ( options = {} ); |
|
1770 |
|
1771 var toRemove = []; |
|
1772 |
|
1773 //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options ); |
|
1774 _.each( models, function( model ) { |
|
1775 model = this.get( model ) || this.get( model.cid ); |
|
1776 model && toRemove.push( model ); |
|
1777 }, this ); |
|
1778 |
|
1779 if ( toRemove.length ) { |
|
1780 remove.call( this, toRemove, options ); |
|
1781 |
|
1782 _.each( toRemove, function( model ) { |
|
1783 this.trigger('relational:remove', model, this, options); |
|
1784 }, this ); |
|
1785 } |
|
1786 |
|
1787 return this; |
|
1788 }; |
|
1789 |
|
1790 /** |
|
1791 * Override 'Backbone.Collection.reset' to trigger 'relational:reset'. |
|
1792 */ |
|
1793 var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset; |
|
1794 Backbone.Collection.prototype.reset = function( models, options ) { |
|
1795 options = _.extend( { merge: true }, options ); |
|
1796 reset.call( this, models, options ); |
|
1797 |
|
1798 if ( this.model.prototype instanceof Backbone.RelationalModel ) { |
|
1799 this.trigger( 'relational:reset', this, options ); |
|
1800 } |
|
1801 |
|
1802 return this; |
|
1803 }; |
|
1804 |
|
1805 /** |
|
1806 * Override 'Backbone.Collection.sort' to trigger 'relational:reset'. |
|
1807 */ |
|
1808 var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort; |
|
1809 Backbone.Collection.prototype.sort = function( options ) { |
|
1810 sort.call( this, options ); |
|
1811 |
|
1812 if ( this.model.prototype instanceof Backbone.RelationalModel ) { |
|
1813 this.trigger( 'relational:reset', this, options ); |
|
1814 } |
|
1815 |
|
1816 return this; |
|
1817 }; |
|
1818 |
|
1819 /** |
|
1820 * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations |
|
1821 * are ready. |
|
1822 */ |
|
1823 var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger; |
|
1824 Backbone.Collection.prototype.trigger = function( eventName ) { |
|
1825 // Short-circuit if this Collection doesn't hold RelationalModels |
|
1826 if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) { |
|
1827 return trigger.apply( this, arguments ); |
|
1828 } |
|
1829 |
|
1830 if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) { |
|
1831 var dit = this, |
|
1832 args = arguments; |
|
1833 |
|
1834 if ( _.isObject( args[ 3 ] ) ) { |
|
1835 args = _.toArray( args ); |
|
1836 // the fourth argument is the option object. |
|
1837 // we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked |
|
1838 args[ 3 ] = _.clone( args[ 3 ] ); |
|
1839 } |
|
1840 |
|
1841 Backbone.Relational.eventQueue.add( function() { |
|
1842 trigger.apply( dit, args ); |
|
1843 }); |
|
1844 } |
|
1845 else { |
|
1846 trigger.apply( this, arguments ); |
|
1847 } |
|
1848 |
|
1849 return this; |
|
1850 }; |
|
1851 |
|
1852 // Override .extend() to automatically call .setup() |
|
1853 Backbone.RelationalModel.extend = function( protoProps, classProps ) { |
|
1854 var child = Backbone.Model.extend.apply( this, arguments ); |
|
1855 |
|
1856 child.setup( this ); |
|
1857 |
|
1858 return child; |
|
1859 }; |
|
1860 })(); |