forked from PaulUithol/Backbone-relational
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-relational.js
executable file
·2082 lines (1790 loc) · 67.8 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
/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */
/**
* Backbone-relational.js 0.10.0
* (c) 2011-2014 Paul Uithol and contributors (https://github.com/PaulUithol/Backbone-relational/graphs/contributors)
*
* 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.
*
* Example:
*
Zoo = Backbone.Relational.Model.extend({
relations: [ {
type: Backbone.HasMany,
key: 'animals',
relatedModel: 'Animal',
reverseRelation: {
key: 'livesIn',
includeInJSON: 'id'
// 'relatedModel' is automatically set to 'Zoo'; the 'relationType' to 'HasOne'.
}
} ],
toString: function() {
return this.get( 'name' );
}
});
Animal = Backbone.Relational.Model.extend({
toString: function() {
return this.get( 'species' );
}
});
// Creating the zoo will give it a collection with one animal in it: the monkey.
// The animal created after that has a relation `livesIn` that points to the zoo it's currently associated with.
// If you instantiate (or fetch) the zebra later, it will automatically be added.
var zoo = new Zoo({
name: 'Artis',
animals: [ { id: 'monkey-1', species: 'Chimp' }, 'lion-1', 'zebra-1' ]
});
var lion = new Animal( { id: 'lion-1', species: 'Lion' } ),
monkey = zoo.get( 'animals' ).first(),
sameZoo = lion.get( 'livesIn' );
*/
( function( factory ) {
// Establish the root object, `window` (`self`) in the browser, or `global` on the server.
// We use `self` instead of `window` for `WebWorker` support.
var root = (typeof self == 'object' && self.self == self && self) ||
(typeof global == 'object' && global.global == global && global);
// Set up Backbone-relational for the environment. Start with AMD.
if ( typeof define === 'function' && define.amd ) {
define( [ 'exports', 'backbone', 'underscore' ], function(exports, Backbone, _){
factory(exports, Backbone, _, root);
});
}
// Next for Node.js or CommonJS.
else if ( typeof exports !== 'undefined' ) {
factory( exports, require( 'backbone' ), require( 'underscore' ), root );
}
// Finally, as a browser global. Use `root` here as it references `window`.
else {
root.Backbone.Relational = factory( {} , root.Backbone, root._, root );
}
}( function( module, Backbone, _, root ) {
"use strict";
module.Collection = Backbone.Collection.extend();
module.showWarnings = true;
/**
* Semaphore mixin; can be used as both binary and counting.
**/
module.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').
*/
module.BlockingQueue = function() {
this._queue = [];
};
_.extend( module.BlockingQueue.prototype, module.Semaphore, {
_queue: null,
add: function( func ) {
if ( this.isBlocked() ) {
this._queue.push( func );
}
else {
func();
}
},
// Some of the queued events may trigger other blocking events. By
// copying the queue here it allows queued events to process closer to
// the natural order.
//
// queue events [ 'A', 'B', 'C' ]
// A handler of 'B' triggers 'D' and 'E'
// By copying `this._queue` this executes:
// [ 'A', 'B', 'D', 'E', 'C' ]
// The same order the would have executed if they didn't have to be
// delayed and queued.
process: function() {
var queue = this._queue;
this._queue = [];
while ( queue && queue.length ) {
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 'change:<key>')
* until the top-level object is fully initialized (see 'Backbone.Relational.Model').
*/
module.eventQueue = new module.BlockingQueue();
/**
* Backbone.Store keeps track of all created (and destruction of) Backbone.Relational.Model.
* Handles lookup for relations.
*/
module.Store = function() {
this._collections = [];
this._reverseRelations = [];
this._orphanRelations = [];
this._subModels = [];
this._modelScopes = [ root ];
};
_.extend( module.Store.prototype, Backbone.Events, {
/**
* Create a new `Relation`.
* @param {Backbone.Relational.Model} [model]
* @param {Object} relation
* @param {Object} [options]
*/
initializeRelation: function( model, relation, options ) {
var type = !_.isString( relation.type ) ? relation.type : module[ relation.type ] || this.getObjectByName( relation.type );
if ( type && type.prototype instanceof module.Relation ) {
var rel = new type( model, relation, options ); // Also pushes the new Relation into `model._relations`
}
else {
module.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation );
}
},
/**
* Add a scope for `getObjectByName` to look for model types by name.
* @param {Object} scope
*/
addModelScope: function( scope ) {
this._modelScopes.push( scope );
},
/**
* Remove a scope.
* @param {Object} scope
*/
removeModelScope: function( scope ) {
this._modelScopes = _.without( this._modelScopes, 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.Relational.Model} subModelTypes
* @param {Backbone.Relational.Model} 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.Relational.Model} modelType
*/
setupSuperModel: function( modelType ) {
_.find( this._subModels, function( subModelDef ) {
return _.filter( 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 ).length;
}, 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.Relational.Model} 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 );
this._addRelation( relation.model, relation );
this.retroFitRelation( relation );
}
},
/**
* Deposit a `relation` for which the `relatedModel` can't be resolved at the moment.
*
* @param {Object} relation
*/
addOrphanRelation: function( relation ) {
var exists = _.any( this._orphanRelations, function( rel ) {
return _.all( relation || [], function( val, key ) {
return val === rel[ key ];
});
});
if ( !exists && relation.model && relation.type ) {
this._orphanRelations.push( relation );
}
},
/**
* Try to initialize any `_orphanRelation`s
*/
processOrphanRelations: function() {
// Make sure to operate on a copy since we're removing while iterating
_.each( this._orphanRelations.slice( 0 ), function( rel ) {
var relatedModel = module.store.getObjectByName( rel.relatedModel );
if ( relatedModel ) {
this.initializeRelation( null, rel );
this._orphanRelations = _.without( this._orphanRelations, rel );
}
}, this );
},
/**
*
* @param {Backbone.Relational.Model.constructor} type
* @param {Object} relation
* @private
*/
_addRelation: function( type, relation ) {
if ( !type.prototype.relations ) {
type.prototype.relations = [];
}
type.prototype.relations.push( relation );
_.each( type._subModels || [], function( subModel ) {
this._addRelation( subModel, relation );
}, this );
},
/**
* 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, false );
coll && coll.each( function( model ) {
if ( !( model instanceof relation.model ) ) {
return;
}
var rel = new relation.type( model, relation );
}, this );
},
/**
* Find the Store's collection for a certain type of model.
* @param {Backbone.Relational.Model} type
* @param {Boolean} [create=true] Should a collection be created if none is found?
* @return {module.Collection} A collection if found (or applicable for 'model'), or null
*/
getCollection: function( type, create ) {
if ( type instanceof module.Model ) {
type = type.constructor;
}
var rootModel = type;
while ( rootModel._superModel ) {
rootModel = rootModel._superModel;
}
var coll = _.find( this._collections, function( item ) {
return item.model === rootModel;
});
if ( !coll && create !== false ) {
coll = this._createCollection( rootModel );
}
return coll;
},
/**
* Find a model type on one of the modelScopes by name. Names are split 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 module.Model ) {
type = type.constructor;
}
// Type should inherit from Backbone.Relational.Model.
if ( type.prototype instanceof module.Model ) {
coll = new module.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.Relational.Model} item
* @return {String|Number}
*/
resolveIdForItem: function( type, item ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : null;
if ( id === null ) {
if ( item instanceof module.Model ) {
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;
},
/**
* Find a specific model of a certain `type` in the store
* @param type
* @param {String|Number|Object|Backbone.Relational.Model} item
*/
find: function( type, item ) {
var id = this.resolveIdForItem( type, item ),
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 its appropriate collection. Retain the original contents of 'model.collection'.
* @param {Backbone.Relational.Model} model
*/
register: function( model ) {
var coll = this.getCollection( model );
if ( coll ) {
var modelColl = model.collection;
coll.add( model );
model.collection = modelColl;
}
},
/**
* Check if the given model may use the given `id`
* @param model
* @param [id]
*/
checkId: function( model, id ) {
var coll = this.getCollection( model ),
duplicate = coll && coll.get( id );
if ( duplicate && model !== duplicate ) {
if ( module.showWarnings && typeof console !== 'undefined' ) {
console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model );
}
throw new Error( "Cannot instantiate more than one Backbone.Relational.Model with the same id per type!" );
}
},
/**
* Explicitly update a model's id in its store collection
* @param {Backbone.Relational.Model} model
*/
update: function( model ) {
var coll = this.getCollection( model );
// Register a model if it isn't yet (which happens if it was created without an id).
if ( !coll.contains( model ) ) {
this.register( model );
}
// This triggers updating the lookup indices kept in a collection
coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
// Trigger an event on model so related models (having the model's new id in their keyContents) can add it.
model.trigger( 'relational:change:id', model, coll );
},
/**
* Unregister from the store: a specific model, a collection, or a model type.
* @param {Backbone.Relational.Model|Backbone.Relational.Model.constructor|module.Collection} type
*/
unregister: function( type ) {
var coll,
models;
if ( type instanceof Backbone.Model ) {
coll = this.getCollection( type );
models = [ type ];
}
else if ( type instanceof module.Collection ) {
coll = this.getCollection( type.model );
models = _.clone( type.models );
}
else {
coll = this.getCollection( type );
models = _.clone( coll.models );
}
_.each( models, function( model ) {
this.stopListening( model );
_.invoke( model.getRelations(), 'stopListening' );
}, this );
// If we've unregistered an entire store collection, reset the collection (which is much faster).
// Otherwise, remove each model one by one.
if ( _.contains( this._collections, type ) ) {
coll.reset( [] );
}
else {
_.each( models, function( model ) {
if ( coll.get( model ) ) {
coll.remove( model );
}
else {
coll.trigger( 'relational:remove', model, coll );
}
}, this );
}
},
/**
* Reset the `store` to it's original state. The `reverseRelations` are kept though, since attempting to
* re-initialize these on models would lead to a large amount of warnings.
*/
reset: function() {
this.stopListening();
// Unregister each collection to remove event listeners
_.each( this._collections, function( coll ) {
this.unregister( coll );
}, this );
this._collections = [];
this._subModels = [];
this._modelScopes = [ root ];
}
});
module.store = new module.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.Relational.Model} [instance] Model that this relation is created for. If no model is supplied,
* Relation just tries to instantiate it's `reverseRelation` if specified, and bails out after that.
* @param {Object} options
* @param {string} options.key
* @param {Backbone.Relational.Model.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').
* @param {Object} opts
*/
module.Relation = function( instance, options, opts ) {
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.options = _.defaults( options, this.options, module.Relation.prototype.options );
this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type :
module[ this.reverseRelation.type ] || module.store.getObjectByName( this.reverseRelation.type );
this.key = this.options.key;
this.keySource = this.options.keySource || this.key;
this.keyDestination = this.options.keyDestination || this.keySource || this.key;
this.model = this.options.model || this.instance.constructor;
this.relatedModel = this.options.relatedModel;
if(_.isUndefined(this.relatedModel)){
this.relatedModel = this.model;
}
if ( _.isFunction( this.relatedModel ) && !( this.relatedModel.prototype instanceof module.Model ) ) {
this.relatedModel = _.result( this, 'relatedModel' );
}
if ( _.isString( this.relatedModel ) ) {
this.relatedModel = module.store.getObjectByName( this.relatedModel );
}
if ( !this.checkPreconditions() ) {
return;
}
// Add the reverse relation on 'relatedModel' to the store's reverseRelations
if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) {
module.store.addReverseRelation( _.defaults( {
isAutoRelation: true,
model: this.relatedModel,
relatedModel: this.model,
reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation
},
this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
) );
}
if ( instance ) {
var contentKey = this.keySource;
if ( contentKey !== this.key && _.isObject( this.instance.get( this.key ) ) ) {
contentKey = this.key;
}
this.setKeyContents( this.instance.get( contentKey ) );
this.relatedCollection = module.store.getCollection( this.relatedModel );
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.keySource !== this.key ) {
delete this.instance.attributes[ this.keySource ];
}
// Add this Relation to instance._relations
this.instance._relations[ this.key ] = this;
this.initialize( opts );
if ( this.options.autoFetch ) {
this.instance.getAsync( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} );
}
// When 'relatedModel' are created or destroyed, check if it affects this relation.
this.listenTo( this.instance, 'destroy', this.destroy )
.listenTo( this.relatedCollection, 'relational:add relational:change:id', this.tryAddRelated )
.listenTo( this.relatedCollection, 'relational:remove', this.removeRelated );
}
};
// Fix inheritance :\
module.Relation.extend = Backbone.Model.extend;
// Set up all inheritable **Backbone.Relation** properties and methods.
_.extend( module.Relation.prototype, Backbone.Events, module.Semaphore, {
options: {
createModels: true,
includeInJSON: true,
isAutoRelation: false,
autoFetch: false,
parse: false
},
instance: null,
key: null,
keyContents: null,
relatedModel: null,
relatedCollection: null,
reverseRelation: null,
related: null,
/**
* 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 = module.showWarnings && typeof console !== 'undefined';
if ( !m || !k || !rm ) {
warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm );
return false;
}
// Check if the type in 'model' inherits from Backbone.Relational.Model
if ( !( m.prototype instanceof module.Model ) ) {
warn && console.warn( 'Relation=%o: model does not inherit from Backbone.Relational.Model (%o).', this, i );
return false;
}
// Check if the type in 'relatedModel' inherits from Backbone.Relational.Model
if ( !( rm.prototype instanceof module.Model ) ) {
warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.Relational.Model (%o).', this, rm );
return false;
}
// Check if this is not a HasMany, and the reverse relation is HasMany as well
if ( this instanceof module.HasMany && this.reverseRelation.type === module.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 relationship on a `key` that's already used.
if ( i && _.keys( i._relations ).length ) {
var existing = _.find( i._relations, function( rel ) {
return rel.key === k;
}, this );
if ( existing ) {
warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.',
this, k, i, existing );
return false;
}
}
return true;
},
/**
* Set the related model(s) for this relation
* @param {Backbone.Model|module.Collection} related
*/
setRelated: function( related ) {
this.related = related;
this.instance.attributes[ this.key ] = related;
},
/**
* 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 ) {
return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
this.key === relation.reverseRelation.key;
},
/**
* Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
* @param {Backbone.Relational.Model} [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 module.Collection), or wrap 'this.related' in an array.
var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] ),
relations = null,
relation = null;
for( var i = 0; i < ( models || [] ).length; i++ ) {
relations = models[ i ].getRelations() || [];
for( var j = 0; j < relations.length; j++ ) {
relation = relations[ j ];
if ( this._isReverseRelation( relation ) ) {
reverseRelations.push( relation );
}
}
}
return reverseRelations;
},
/**
* When `this.instance` is destroyed, cleanup our relations.
* Get reverse relation, call removeRelated on each.
*/
destroy: function() {
this.stopListening();
if ( this instanceof module.HasOne ) {
this.setRelated( null );
}
else if ( this instanceof module.HasMany ) {
this.setRelated( this._prepareCollection() );
}
_.each( this.getReverseRelations(), function( relation ) {
relation.removeRelated( this.instance );
}, this );
}
});
module.HasOne = module.Relation.extend({
options: {
reverseRelation: { type: 'HasMany' }
},
initialize: function( opts ) {
this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
var related = this.findRelated( opts );
this.setRelated( related );
// Notify new 'related' object of the new relation.
_.each( this.getReverseRelations(), function( relation ) {
relation.addRelated( this.instance, opts );
}, this );
},
/**
* Find related Models.
* @param {Object} [options]
* @return {Backbone.Model}
*/
findRelated: function( options ) {
var related = null;
options = _.defaults( { parse: this.options.parse }, options );
if ( this.keyContents instanceof this.relatedModel ) {
related = this.keyContents;
}
else if ( this.keyContents || this.keyContents === 0 ) { // since 0 can be a valid `id` as well
var opts = _.defaults( { create: this.options.createModels }, options );
related = this.relatedModel.findOrCreate( this.keyContents, opts );
}
// Nullify `keyId` if we have a related model; in case it was already part of the relation
if ( related ) {
this.keyId = null;
}
return related;
},
/**
* Normalize and reduce `keyContents` to an `id`, for easier comparison
* @param {String|Number|Backbone.Model} keyContents
*/
setKeyContents: function( keyContents ) {
this.keyContents = keyContents;
this.keyId = module.store.resolveIdForItem( this.relatedModel, this.keyContents );
},
/**
* Event handler for `change:<key>`.
* 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 = options ? _.clone( 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 ),
oldRelated = changed ? this.related : options.__related;
if ( changed ) {
this.setKeyContents( attr );
var related = this.findRelated( options );
this.setRelated( related );
}
// Notify old 'related' object of the terminated relation
if ( oldRelated && this.related !== oldRelated ) {
_.each( this.getReverseRelations( oldRelated ), function( relation ) {
relation.removeRelated( this.instance, null, 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 'change:<key>' event if 'related' was updated
if ( !options.silent && this.related !== oldRelated ) {
var dit = this;
this.changed = true;
module.eventQueue.add( function() {
dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true );
dit.changed = false;
});
}
this.release();
},
/**
* If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
*/
tryAddRelated: function( model, coll, options ) {
if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well
this.addRelated( model, options );
this.keyId = null;
}
},
addRelated: function( model, options ) {
// Allow 'model' to set up its relations before proceeding.
// (which can result in a call to 'addRelated' from a relation of 'model')
var dit = this;
model.queue( function() {
if ( model !== dit.related ) {
var oldRelated = dit.related || null;
dit.setRelated( model );
dit.onChange( dit.instance, model, _.defaults( { __related: oldRelated }, options ) );
}
});
},
removeRelated: function( model, coll, options ) {
if ( !this.related ) {
return;
}
if ( model === this.related ) {
var oldRelated = this.related || null;
this.setRelated( null );
this.onChange( this.instance, model, _.defaults( { __related: oldRelated }, options ) );
}
}
});
module.HasMany = module.Relation.extend({
collectionType: null,
options: {
reverseRelation: { type: 'HasOne' },
collectionType: module.Collection,
collectionKey: true,
collectionOptions: {}
},
initialize: function( opts ) {
this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
// Handle a custom 'collectionType'
this.collectionType = this.options.collectionType;
if ( _.isFunction( this.collectionType ) && this.collectionType !== module.Collection && !( this.collectionType.prototype instanceof module.Collection ) ) {
this.collectionType = _.result( this, 'collectionType' );
}
if ( _.isString( this.collectionType ) ) {
this.collectionType = module.store.getObjectByName( this.collectionType );
}
if ( this.collectionType !== module.Collection && !( this.collectionType.prototype instanceof module.Collection ) ) {
throw new Error( '`collectionType` must inherit from module.Collection' );
}
var related = this.findRelated( opts );
this.setRelated( related );
},
/**
* 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 {module.Collection} [collection]
* @return {module.Collection}
*/
_prepareCollection: function( collection ) {
if ( this.related ) {
this.stopListening( this.related );
}
if ( !collection || !( collection instanceof module.Collection ) ) {
var options = _.isFunction( this.options.collectionOptions ) ?
this.options.collectionOptions( this.instance ) : this.options.collectionOptions;
collection = new this.collectionType( null, options );
}
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 ( module.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;
}
}
this.listenTo( collection, 'relational:add', this.handleAddition )
.listenTo( collection, 'relational:remove', this.handleRemoval )
.listenTo( collection, 'relational:reset', this.handleReset );
return collection;
},