-
Notifications
You must be signed in to change notification settings - Fork 330
/
backbone-relational.js
executable file
·1706 lines (1463 loc) · 54.9 KB
/
backbone-relational.js
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Backbone-relational.js 0.6.0
* (c) 2011 Paul Uithol
*
* Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
* For details and documentation: https://github.com/PaulUithol/Backbone-relational.
* Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
*/
( function( undefined ) {
"use strict";
/**
* CommonJS shim
**/
var _, Backbone, exports;
// Support loading requirements using `require` compatible implementations.
// In server environments, `window` is not defined; in browser environments, check for the presence of `require`.
if ( typeof window === 'undefined' || typeof require !== 'undefined' ) {
_ = require( 'underscore' );
Backbone = require( 'backbone' );
exports = module.exports = Backbone;
}
else {
_ = window._;
Backbone = window.Backbone;
exports = window;
}
Backbone.Relational = {
showWarnings: true
};
/**
* Semaphore mixin; can be used as both binary and counting.
**/
Backbone.Semaphore = {
_permitsAvailable: null,
_permitsUsed: 0,
acquire: function() {
if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) {
throw new Error( 'Max permits acquired' );
}
else {
this._permitsUsed++;
}
},
release: function() {
if ( this._permitsUsed === 0 ) {
throw new Error( 'All permits released' );
}
else {
this._permitsUsed--;
}
},
isLocked: function() {
return this._permitsUsed > 0;
},
setAvailablePermits: function( amount ) {
if ( this._permitsUsed > amount ) {
throw new Error( 'Available permits cannot be less than used permits' );
}
this._permitsAvailable = amount;
}
};
/**
* A BlockingQueue that accumulates items while blocked (via 'block'),
* and processes them when unblocked (via 'unblock').
* Process can also be called manually (via 'process').
*/
Backbone.BlockingQueue = function() {
this._queue = [];
};
_.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, {
_queue: null,
add: function( func ) {
if ( this.isBlocked() ) {
this._queue.push( func );
}
else {
func();
}
},
process: function() {
while ( this._queue && this._queue.length ) {
this._queue.shift()();
}
},
block: function() {
this.acquire();
},
unblock: function() {
this.release();
if ( !this.isBlocked() ) {
this.process();
}
},
isBlocked: function() {
return this.isLocked();
}
});
/**
* Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'update:<key>')
* until the top-level object is fully initialized (see 'Backbone.RelationalModel').
*/
Backbone.Relational.eventQueue = new Backbone.BlockingQueue();
/**
* Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel.
* Handles lookup for relations.
*/
Backbone.Store = function() {
this._collections = [];
this._reverseRelations = [];
this._subModels = [];
this._modelScopes = [ exports ];
};
_.extend( Backbone.Store.prototype, Backbone.Events, {
addModelScope: function( scope ) {
this._modelScopes.push( scope );
},
/**
* Add a set of subModelTypes to the store, that can be used to resolve the '_superModel'
* for a model later in 'setupSuperModel'.
*
* @param {Backbone.RelationalModel} subModelTypes
* @param {Backbone.RelationalModel} superModelType
*/
addSubModels: function( subModelTypes, superModelType ) {
this._subModels.push({
'superModelType': superModelType,
'subModels': subModelTypes
});
},
/**
* Check if the given modelType is registered as another model's subModel. If so, add it to the super model's
* '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'.
*
* @param {Backbone.RelationalModel} modelType
*/
setupSuperModel: function( modelType ) {
_.find( this._subModels || [], function( subModelDef ) {
return _.find( subModelDef.subModels || [], function( subModelTypeName, typeValue ) {
var subModelType = this.getObjectByName( subModelTypeName );
if ( modelType === subModelType ) {
// Set 'modelType' as a child of the found superModel
subModelDef.superModelType._subModels[ typeValue ] = modelType;
// Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'.
modelType._superModel = subModelDef.superModelType;
modelType._subModelTypeValue = typeValue;
modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute;
return true;
}
}, this );
}, this );
},
/**
* Add a reverse relation. Is added to the 'relations' property on model's prototype, and to
* existing instances of 'model' in the store as well.
* @param {Object} relation
* @param {Backbone.RelationalModel} relation.model
* @param {String} relation.type
* @param {String} relation.key
* @param {String|Object} relation.relatedModel
*/
addReverseRelation: function( relation ) {
var exists = _.any( this._reverseRelations || [], function( rel ) {
return _.all( relation || [], function( val, key ) {
return val === rel[ key ];
});
});
if ( !exists && relation.model && relation.type ) {
this._reverseRelations.push( relation );
var addRelation = function( model, relation ) {
if ( !model.prototype.relations ) {
model.prototype.relations = [];
}
model.prototype.relations.push( relation );
_.each( model._subModels || [], function( subModel ) {
addRelation( subModel, relation );
}, this );
};
addRelation( relation.model, relation );
this.retroFitRelation( relation );
}
},
/**
* Add a 'relation' to all existing instances of 'relation.model' in the store
* @param {Object} relation
*/
retroFitRelation: function( relation ) {
var coll = this.getCollection( relation.model );
coll.each( function( model ) {
if ( !( model instanceof relation.model ) ) {
return;
}
new relation.type( model, relation );
}, this);
},
/**
* Find the Store's collection for a certain type of model.
* @param {Backbone.RelationalModel} model
* @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
*/
getCollection: function( model ) {
if ( model instanceof Backbone.RelationalModel ) {
model = model.constructor;
}
var rootModel = model;
while ( rootModel._superModel ) {
rootModel = rootModel._superModel;
}
var coll = _.detect( this._collections, function( c ) {
return c.model === rootModel;
});
if ( !coll ) {
coll = this._createCollection( rootModel );
}
return coll;
},
/**
* Find a type on the global object by name. Splits name on dots.
* @param {String} name
* @return {Object}
*/
getObjectByName: function( name ) {
var parts = name.split( '.' ),
type = null;
_.find( this._modelScopes || [], function( scope ) {
type = _.reduce( parts || [], function( memo, val ) {
return memo ? memo[ val ] : undefined;
}, scope );
if ( type && type !== scope ) {
return true;
}
}, this );
return type;
},
_createCollection: function( type ) {
var coll;
// If 'type' is an instance, take its constructor
if ( type instanceof Backbone.RelationalModel ) {
type = type.constructor;
}
// Type should inherit from Backbone.RelationalModel.
if ( type.prototype instanceof Backbone.RelationalModel ) {
coll = new Backbone.Collection();
coll.model = type;
this._collections.push( coll );
}
return coll;
},
/**
* Find the attribute that is to be used as the `id` on a given object
* @param type
* @param {String|Number|Object|Backbone.RelationalModel} item
* @return {String|Number}
*/
resolveIdForItem: function( type, item ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : null;
if ( id === null ) {
if ( item instanceof Backbone.RelationalModel ) {
id = item.id;
}
else if ( _.isObject( item ) ) {
id = item[ type.prototype.idAttribute ];
}
}
// Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179')
if ( !id && id !== 0 ) {
id = null;
}
return id;
},
/**
*
* @param type
* @param {String|Number|Object|Backbone.RelationalModel} item
*/
find: function( type, item ) {
var id = this.resolveIdForItem( type, item );
var coll = this.getCollection( type );
// Because the found object could be of any of the type's superModel
// types, only return it if it's actually of the type asked for.
if ( coll ) {
var obj = coll.get( id );
if ( obj instanceof type ) {
return obj;
}
}
return null;
},
/**
* Add a 'model' to it's appropriate collection. Retain the original contents of 'model.collection'.
* @param {Backbone.RelationalModel} model
*/
register: function( model ) {
var coll = this.getCollection( model );
if ( coll ) {
if ( coll.get( model ) ) {
throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" );
}
var modelColl = model.collection;
coll.add( model );
model.bind( 'destroy', this.unregister, this );
model.collection = modelColl;
}
},
/**
* Explicitly update a model's id in it's store collection
* @param {Backbone.RelationalModel} model
*/
update: function( model ) {
var coll = this.getCollection( model );
coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
},
/**
* Remove a 'model' from the store.
* @param {Backbone.RelationalModel} model
*/
unregister: function( model ) {
model.unbind( 'destroy', this.unregister );
var coll = this.getCollection( model );
coll && coll.remove( model );
}
});
Backbone.Relational.store = new Backbone.Store();
/**
* The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events
* are used to regulate addition and removal of models from relations.
*
* @param {Backbone.RelationalModel} instance
* @param {Object} options
* @param {string} options.key
* @param {Backbone.RelationalModel.constructor} options.relatedModel
* @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids.
* @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store.
* @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate
* the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs
* {Backbone.Relation|String} type ('HasOne' or 'HasMany').
*/
Backbone.Relation = function( instance, options ) {
this.instance = instance;
// Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype
options = _.isObject( options ) ? options : {};
this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation );
this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type :
Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type );
this.model = options.model || this.instance.constructor;
this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options );
this.key = this.options.key;
this.keySource = this.options.keySource || this.key;
this.keyDestination = this.options.keyDestination || this.keySource || this.key;
// 'exports' should be the global object where 'relatedModel' can be found on if given as a string.
this.relatedModel = this.options.relatedModel;
if ( _.isString( this.relatedModel ) ) {
this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel );
}
if ( !this.checkPreconditions() ) {
return false;
}
if ( instance ) {
var contentKey = this.keySource;
if ( contentKey !== this.key && typeof this.instance.get( this.key ) === 'object' ) {
contentKey = this.key;
}
this.keyContents = this.instance.get( contentKey );
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.keySource !== this.key ) {
this.instance.unset( this.keySource, { silent: true } );
}
// Add this Relation to instance._relations
this.instance._relations.push( this );
}
// Add the reverse relation on 'relatedModel' to the store's reverseRelations
if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) {
Backbone.Relational.store.addReverseRelation( _.defaults( {
isAutoRelation: true,
model: this.relatedModel,
relatedModel: this.model,
reverseRelation: this.options // current relation is the 'reverseRelation' for it's own reverseRelation
},
this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
) );
}
_.bindAll( this, '_modelRemovedFromCollection', '_relatedModelAdded', '_relatedModelRemoved' );
if ( instance ) {
this.initialize();
// When a model in the store is destroyed, check if it is 'this.instance'.
Backbone.Relational.store.getCollection( this.instance )
.bind( 'relational:remove', this._modelRemovedFromCollection );
// When 'relatedModel' are created or destroyed, check if it affects this relation.
Backbone.Relational.store.getCollection( this.relatedModel )
.bind( 'relational:add', this._relatedModelAdded )
.bind( 'relational:remove', this._relatedModelRemoved );
}
};
// Fix inheritance :\
Backbone.Relation.extend = Backbone.Model.extend;
// Set up all inheritable **Backbone.Relation** properties and methods.
_.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, {
options: {
createModels: true,
includeInJSON: true,
isAutoRelation: false
},
instance: null,
key: null,
keyContents: null,
relatedModel: null,
reverseRelation: null,
related: null,
_relatedModelAdded: function( model, coll, options ) {
// Allow 'model' to set up it's relations, before calling 'tryAddRelated'
// (which can result in a call to 'addRelated' on a relation of 'model')
var dit = this;
model.queue( function() {
dit.tryAddRelated( model, options );
});
},
_relatedModelRemoved: function( model, coll, options ) {
this.removeRelated( model, options );
},
_modelRemovedFromCollection: function( model ) {
if ( model === this.instance ) {
this.destroy();
}
},
/**
* Check several pre-conditions.
* @return {Boolean} True if pre-conditions are satisfied, false if they're not.
*/
checkPreconditions: function() {
var i = this.instance,
k = this.key,
m = this.model,
rm = this.relatedModel,
warn = Backbone.Relational.showWarnings && typeof console !== 'undefined';
if ( !m || !k || !rm ) {
warn && console.warn( 'Relation=%o; no model, key or relatedModel (%o, %o, %o)', this, m, k, rm );
return false;
}
// Check if the type in 'model' inherits from Backbone.RelationalModel
if ( !( m.prototype instanceof Backbone.RelationalModel ) ) {
warn && console.warn( 'Relation=%o; model does not inherit from Backbone.RelationalModel (%o)', this, i );
return false;
}
// Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) {
warn && console.warn( 'Relation=%o; relatedModel does not inherit from Backbone.RelationalModel (%o)', this, rm );
return false;
}
// Check if this is not a HasMany, and the reverse relation is HasMany as well
if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) {
warn && console.warn( 'Relation=%o; relation is a HasMany, and the reverseRelation is HasMany as well.', this );
return false;
}
// Check if we're not attempting to create a duplicate relationship
if ( i && i._relations.length ) {
var exists = _.any( i._relations || [], function( rel ) {
var hasReverseRelation = this.reverseRelation.key && rel.reverseRelation.key;
return rel.relatedModel === rm && rel.key === k &&
( !hasReverseRelation || this.reverseRelation.key === rel.reverseRelation.key );
}, this );
if ( exists ) {
warn && console.warn( 'Relation=%o between instance=%o.%s and relatedModel=%o.%s already exists',
this, i, k, rm, this.reverseRelation.key );
return false;
}
}
return true;
},
/**
* Set the related model(s) for this relation
* @param {Backbone.Mode|Backbone.Collection} related
* @param {Object} [options]
*/
setRelated: function( related, options ) {
this.related = related;
this.instance.acquire();
this.instance.set( this.key, related, _.defaults( options || {}, { silent: true } ) );
this.instance.release();
},
/**
* Determine if a relation (on a different RelationalModel) is the reverse
* relation of the current one.
* @param {Backbone.Relation} relation
* @return {Boolean}
*/
_isReverseRelation: function( relation ) {
if ( relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
this.key === relation.reverseRelation.key ) {
return true;
}
return false;
},
/**
* Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
* @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model.
* If not specified, 'this.related' is used.
* @return {Backbone.Relation[]}
*/
getReverseRelations: function( model ) {
var reverseRelations = [];
// Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array.
var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] );
_.each( models || [], function( related ) {
_.each( related.getRelations() || [], function( relation ) {
if ( this._isReverseRelation( relation ) ) {
reverseRelations.push( relation );
}
}, this );
}, this );
return reverseRelations;
},
/**
* Rename options.silent to options.silentChange, so events propagate properly.
* (for example in HasMany, from 'addRelated'->'handleAddition')
* @param {Object} [options]
* @return {Object}
*/
sanitizeOptions: function( options ) {
options = options ? _.clone( options ) : {};
if ( options.silent ) {
options.silentChange = true;
delete options.silent;
}
return options;
},
/**
* Rename options.silentChange to options.silent, so events are silenced as intended in Backbone's
* original functions.
* @param {Object} [options]
* @return {Object}
*/
unsanitizeOptions: function( options ) {
options = options ? _.clone( options ) : {};
if ( options.silentChange ) {
options.silent = true;
delete options.silentChange;
}
return options;
},
// Cleanup. Get reverse relation, call removeRelated on each.
destroy: function() {
Backbone.Relational.store.getCollection( this.instance )
.unbind( 'relational:remove', this._modelRemovedFromCollection );
Backbone.Relational.store.getCollection( this.relatedModel )
.unbind( 'relational:add', this._relatedModelAdded )
.unbind( 'relational:remove', this._relatedModelRemoved );
_.each( this.getReverseRelations() || [], function( relation ) {
relation.removeRelated( this.instance );
}, this );
}
});
Backbone.HasOne = Backbone.Relation.extend({
options: {
reverseRelation: { type: 'HasMany' }
},
initialize: function() {
_.bindAll( this, 'onChange' );
this.instance.bind( 'relational:change:' + this.key, this.onChange );
var model = this.findRelated( { silent: true } );
this.setRelated( model );
// Notify new 'related' object of the new relation.
_.each( this.getReverseRelations() || [], function( relation ) {
relation.addRelated( this.instance );
}, this );
},
findRelated: function( options ) {
var item = this.keyContents;
var model = null;
if ( item instanceof this.relatedModel ) {
model = item;
}
else if ( item || item === 0 ) { // since 0 can be a valid `id` as well
model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } );
}
return model;
},
/**
* If the key is changed, notify old & new reverse relations and initialize the new relation
*/
onChange: function( model, attr, options ) {
// Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
if ( this.isLocked() ) {
return;
}
this.acquire();
options = this.sanitizeOptions( options );
// 'options._related' is set by 'addRelated'/'removeRelated'. If it is set, the change
// is the result of a call from a relation. If it's not, the change is the result of
// a 'set' call on this.instance.
var changed = _.isUndefined( options._related );
var oldRelated = changed ? this.related : options._related;
if ( changed ) {
this.keyContents = attr;
// Set new 'related'
if ( attr instanceof this.relatedModel ) {
this.related = attr;
}
else if ( attr ) {
var related = this.findRelated( options );
this.setRelated( related );
}
else {
this.setRelated( null );
}
}
// Notify old 'related' object of the terminated relation
if ( oldRelated && this.related !== oldRelated ) {
_.each( this.getReverseRelations( oldRelated ) || [], function( relation ) {
relation.removeRelated( this.instance, options );
}, this );
}
// Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
// that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
// In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
_.each( this.getReverseRelations() || [], function( relation ) {
relation.addRelated( this.instance, options );
}, this);
// Fire the 'update:<key>' event if 'related' was updated
if ( !options.silentChange && this.related !== oldRelated ) {
var dit = this;
Backbone.Relational.eventQueue.add( function() {
dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options );
});
}
this.release();
},
/**
* If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
*/
tryAddRelated: function( model, options ) {
if ( this.related ) {
return;
}
options = this.sanitizeOptions( options );
var item = this.keyContents;
if ( item || item === 0 ) { // since 0 can be a valid `id` as well
var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
if ( !_.isNull( id ) && model.id === id ) {
this.addRelated( model, options );
}
}
},
addRelated: function( model, options ) {
if ( model !== this.related ) {
var oldRelated = this.related || null;
this.setRelated( model );
this.onChange( this.instance, model, { _related: oldRelated } );
}
},
removeRelated: function( model, options ) {
if ( !this.related ) {
return;
}
if ( model === this.related ) {
var oldRelated = this.related || null;
this.setRelated( null );
this.onChange( this.instance, model, { _related: oldRelated } );
}
}
});
Backbone.HasMany = Backbone.Relation.extend({
collectionType: null,
options: {
reverseRelation: { type: 'HasOne' },
collectionType: Backbone.Collection,
collectionKey: true,
collectionOptions: {}
},
initialize: function() {
_.bindAll( this, 'onChange', 'handleAddition', 'handleRemoval', 'handleReset' );
this.instance.bind( 'relational:change:' + this.key, this.onChange );
// Handle a custom 'collectionType'
this.collectionType = this.options.collectionType;
if ( _.isString( this.collectionType ) ) {
this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType );
}
if ( !this.collectionType.prototype instanceof Backbone.Collection ){
throw new Error( 'collectionType must inherit from Backbone.Collection' );
}
// Handle cases where a model/relation is created with a collection passed straight into 'attributes'
if ( this.keyContents instanceof Backbone.Collection ) {
this.setRelated( this._prepareCollection( this.keyContents ) );
}
else {
this.setRelated( this._prepareCollection() );
}
this.findRelated( { silent: true } );
},
_getCollectionOptions: function() {
return _.isFunction( this.options.collectionOptions ) ?
this.options.collectionOptions( this.instance ) :
this.options.collectionOptions;
},
/**
* Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany.
* If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option.
* @param {Backbone.Collection} [collection]
*/
_prepareCollection: function( collection ) {
if ( this.related ) {
this.related
.unbind( 'relational:add', this.handleAddition )
.unbind( 'relational:remove', this.handleRemoval )
.unbind( 'relational:reset', this.handleReset )
}
if ( !collection || !( collection instanceof Backbone.Collection ) ) {
collection = new this.collectionType( [], this._getCollectionOptions() );
}
collection.model = this.relatedModel;
if ( this.options.collectionKey ) {
var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey;
if ( collection[ key ] && collection[ key ] !== this.instance ) {
if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey );
}
}
else if ( key ) {
collection[ key ] = this.instance;
}
}
collection
.bind( 'relational:add', this.handleAddition )
.bind( 'relational:remove', this.handleRemoval )
.bind( 'relational:reset', this.handleReset );
return collection;
},
findRelated: function( options ) {
if ( this.keyContents ) {
var models = [];
if ( this.keyContents instanceof Backbone.Collection ) {
models = this.keyContents.models;
}
else {
// Handle cases the an API/user supplies just an Object/id instead of an Array
this.keyContents = _.isArray( this.keyContents ) ? this.keyContents : [ this.keyContents ];
// Try to find instances of the appropriate 'relatedModel' in the store
_.each( this.keyContents || [], function( item ) {
var model = null;
if ( item instanceof this.relatedModel ) {
model = item;
}
else if ( item || item === 0 ) { // since 0 can be a valid `id` as well
model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } );
}
if ( model && !this.related.getByCid( model ) && !this.related.get( model ) ) {
models.push( model );
}
}, this );
}
// Add all found 'models' in on go, so 'add' will only be called once (and thus 'sort', etc.)
if ( models.length ) {
options = this.unsanitizeOptions( options );
this.related.add( models, options );
}
}
},
/**
* If the key is changed, notify old & new reverse relations and initialize the new relation
*/
onChange: function( model, attr, options ) {
options = this.sanitizeOptions( options );
this.keyContents = attr;
// Replace 'this.related' by 'attr' if it is a Backbone.Collection
if ( attr instanceof Backbone.Collection ) {
this._prepareCollection( attr );
this.related = attr;
}
// Otherwise, 'attr' should be an array of related object ids.
// Re-use the current 'this.related' if it is a Backbone.Collection, and remove any current entries.
// Otherwise, create a new collection.
else {
var oldIds = {}, newIds = {};
if (!_.isArray( attr ) && attr !== undefined) {
attr = [ attr ];
}
var oldIds;
_.each( attr, function( attributes ) {
newIds[ attributes.id ] = true;
});
var coll = this.related;
if ( coll instanceof Backbone.Collection ) {
// Make sure to operate on a copy since we're removing while iterating
_.each( coll.models.slice(0) , function( model ) {
// When fetch is called with the 'keepNewModels' option, we don't want to remove
// client-created new models when the fetch is completed.
if ( !options.keepNewModels || !model.isNew() ) {
oldIds[ model.id ] = true;
coll.remove( model, { silent: (model.id in newIds) } );
}
});
} else {
coll = this._prepareCollection();
}
_.each( attr, function( attributes ) {
var model = this.relatedModel.findOrCreate( attributes, { create: this.options.createModels } );
if (model) {
coll.add( model, { silent: (attributes.id in oldIds)} );
}
}, this);
this.setRelated( coll );
}
var dit = this;
Backbone.Relational.eventQueue.add( function() {
!options.silentChange && dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options );
});
},
tryAddRelated: function( model, options ) {
options = this.sanitizeOptions( options );
if ( !this.related.getByCid( model ) && !this.related.get( model ) ) {
// Check if this new model was specified in 'this.keyContents'
var item = _.any( this.keyContents || [], function( item ) {
var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
return !_.isNull( id ) && id === model.id;
}, this );
if ( item ) {
this.related.add( model, options );
}
}
},
/**
* When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations.
* (should be 'HasOne', must set 'this.instance' as their related).
*/
handleAddition: function( model, coll, options ) {
//console.debug('handleAddition called; args=%o', arguments);
// Make sure the model is in fact a valid model before continuing.
// (it can be invalid as a result of failing validation in Backbone.Collection._prepareModel)
if ( !( model instanceof Backbone.Model ) ) {
return;
}
options = this.sanitizeOptions( options );
_.each( this.getReverseRelations( model ) || [], function( relation ) {
relation.addRelated( this.instance, options );
}, this );
// Only trigger 'add' once the newly added model is initialized (so, has it's relations set up)
var dit = this;
Backbone.Relational.eventQueue.add( function() {
!options.silentChange && dit.instance.trigger( 'add:' + dit.key, model, dit.related, options );
});
},
/**
* When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations.
* (should be 'HasOne', which should be nullified)
*/
handleRemoval: function( model, coll, options ) {
//console.debug('handleRemoval called; args=%o', arguments);
if ( !( model instanceof Backbone.Model ) ) {
return;
}
options = this.sanitizeOptions( options );
_.each( this.getReverseRelations( model ) || [], function( relation ) {
relation.removeRelated( this.instance, options );
}, this );
var dit = this;
Backbone.Relational.eventQueue.add( function() {
!options.silentChange && dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options );
});
},