forked from PaulUithol/Backbone-relational
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-relational.js
1121 lines (969 loc) · 36.6 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.4.0
* (c) 2011 Paul Uithol
*
* Backbone-relational may be freely distributed under the MIT license.
* For details and documentation: https://github.com/PaulUithol/Backbone-relational.
* Depends on (as in, compeletely useless without) Backbone: https://github.com/documentcloud/backbone.
*/
(function(undefined) {
/**
* CommonJS shim
**/
if ( typeof window === 'undefined' ) {
var _ = require( 'underscore' );
var Backbone = require( 'backbone' );
var exports = module.exports = Backbone;
} else {
var _ = this._;
var Backbone = this.Backbone;
var exports = this;
}
Backbone.Relational = {};
/**
* 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 = [];
};
_.extend( Backbone.Store.prototype, Backbone.Events, {
_collections: null,
_reverseRelations: null,
/**
* 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; required properties:
* - model, type, key and 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 );
if ( !relation.model.prototype.relations ) {
relation.model.prototype.relations = [];
}
relation.model.prototype.relations.push( relation );
this.retroFitRelation( relation );
}
},
/**
* Add a 'relation' to all existing instances of 'relation.model' in the store
*/
retroFitRelation: function( relation ) {
var coll = this.getCollection( relation.model );
coll.each( function( model ) {
var rel = new relation.type( model, relation );
}, this);
},
/**
* Find the Store's collection for a certain type of model.
* @param model {Backbone.RelationalModel}
* @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
*/
getCollection: function( model ) {
var coll = _.detect( this._collections, function( c ) {
// Check if model is the type itself (a ref to the constructor), or is of type c.model
return model === c.model || model.constructor === c.model;
});
if ( !coll ) {
coll = this._createCollection( model );
}
return coll;
},
/**
* Find a type on the global object by name. Splits name on dots.
* @param {string} name
*/
getObjectByName: function( name ) {
var type = _.reduce( name.split( '.' ), function( memo, val ) {
return memo[ val ];
}, exports);
return type !== exports ? type: null;
},
_createCollection: function( type ) {
var coll;
// If 'type' is an instance, take it's constructor
if ( type instanceof Backbone.RelationalModel ) {
type = type.constructor;
}
// Type should inherit from Backbone.RelationalModel.
if ( type.prototype instanceof Backbone.RelationalModel.prototype.constructor ) {
coll = new Backbone.Collection();
coll.model = type;
this._collections.push( coll );
}
return coll;
},
find: function( type, id ) {
var coll = this.getCollection( type );
return coll && coll.get( id );
},
/**
* Add a 'model' to it's appropriate collection. Retain the original contents of 'model.collection'.
*/
register: function( model ) {
var modelColl = model.collection;
var coll = this.getCollection( model );
coll && coll._add( model );
model.bind( 'destroy', this.unregister, this );
model.collection = modelColl;
},
/**
* Explicitly update a model's id in it's store collection
*/
update: function( model ) {
var coll = this.getCollection( model );
coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
},
/**
* Remove a 'model' from the store.
*/
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.
* @param {Backbone.RelationalModel} instance
* @param {object} options.
* Required properties:
* - {string} key
* - {Backbone.RelationalModel.constructor} relatedModel
* Optional properties:
* - {bool} includeInJSON: create objects from the contents of keys if the object is not found in Backbone.store.
* - {bool} createModels: serialize the attributes for related model(s)' in toJSON on create/update, or just their ids.
* - {object} reverseRelation: Specify a bi-directional relation. If provided, Relation will reciprocate
* the relation to the 'relatedModel'. Required and optional properties match 'options', except for:
* - {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 = ( typeof options === 'object' && 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.options = _.defaults( options, this.options, Backbone.Relation.prototype.options );
this.key = this.options.key;
this.keyContents = this.instance.get( 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;
}
// 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.instance.constructor,
reverseRelation: this.options // current relation is the 'reverseRelation' for it's own reverseRelation
},
this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
) );
}
this.initialize();
_.bindAll( this, '_modelRemovedFromCollection', '_relatedModelAdded', '_relatedModelRemoved' );
// 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 {bool} True if pre-conditions are satisfied, false if they're not.
*/
checkPreconditions: function() {
var i = this.instance, k = this.key, rm = this.relatedModel;
if ( !i || !k || !rm ) {
console && console.warn( 'Relation=%o; no instance, key or relatedModel (%o, %o, %o)', this, i, k, rm );
return false;
}
// Check if 'instance' is a Backbone.RelationalModel
if ( !( i instanceof Backbone.RelationalModel ) ) {
console && console.warn( 'Relation=%o; instance=%o is not a Backbone.RelationalModel', this, i );
return false;
}
// Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
if ( !( rm.prototype instanceof Backbone.RelationalModel.prototype.constructor ) ) {
console && 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.prototype.constructor ) {
console && 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._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 ) {
console && 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;
},
setRelated: function( related, options ) {
this.related = related;
var value = {};
value[ this.key ] = related;
this.instance.acquire();
this.instance.set( value, _.defaults( options || {}, { silent: true } ) );
this.instance.release();
},
createModel: function( item ) {
if ( this.options.createModels && typeof( item ) === 'object' ) {
return new this.relatedModel( item );
}
},
/**
* Determine if a relation (on a different RelationalModel) is the reverse
* relation of the current one.
*/
_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 model {Backbone.RelationalModel} Optional; get the reverse relations for a specific model.
* If not specified, 'this.related' is used.
*/
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, so add/remove events propagate properly.
* (for example in HasMany, from 'addRelated'->'handleAddition')
*/
sanitizeOptions: function( options ) {
options || ( options = {} );
if ( options.silent ) {
options = _.extend( {}, options, { silentChange: true } );
delete options.silent;
}
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();
this.setRelated( model );
// Notify new 'related' object of the new relation.
var dit = this;
_.each( dit.getReverseRelations(), function( relation ) {
relation.addRelated( dit.instance );
} );
},
findRelated: function( options ) {
var item = this.keyContents;
var model = null;
if ( item instanceof this.relatedModel ) {
model = item;
}
else if ( item && ( _.isString( item ) || _.isNumber( item ) || typeof( item ) === 'object' ) ) {
// Try to find an instance of the appropriate 'relatedModel' in the store, or create it
var id = _.isString( item ) || _.isNumber( item ) ? item : item[ this.relatedModel.prototype.idAttribute ];
model = Backbone.Relational.store.find( this.relatedModel, id );
if ( model && _.isObject( item ) ) {
model.set( item, options );
}
else if ( !model ) {
model = this.createModel( item );
}
}
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->createModel->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 && ( _.isString( item ) || _.isNumber( item ) || typeof( item ) === 'object' ) ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : item[ this.relatedModel.prototype.idAttribute ];
if ( 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
},
initialize: function() {
_.bindAll( this, 'onChange', 'handleAddition', 'handleRemoval' );
this.instance.bind( 'relational:change:' + this.key, this.onChange );
// Handle a custom 'collectionType'
this.collectionType = this.options.collectionType;
if ( _( this.collectionType ).isString() ) {
this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType );
}
if ( !this.collectionType.prototype instanceof Backbone.Collection.prototype.constructor ){
throw new Error( 'collectionType must inherit from Backbone.Collection' );
}
this.setRelated( this.prepareCollection( new this.collectionType() ) );
this.findRelated();
},
prepareCollection: function( collection ) {
if ( this.related ) {
this.related.unbind( 'relational:add', this.handleAddition ).unbind('relational:remove', this.handleRemoval );
}
collection.reset();
collection.model = this.relatedModel;
collection.bind( 'relational:add', this.handleAddition ).bind('relational:remove', this.handleRemoval );
return collection;
},
findRelated: function( options ) {
if ( this.keyContents && _.isArray( this.keyContents ) ) {
// Try to find instances of the appropriate 'relatedModel' in the store
_.each( this.keyContents, function( item ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : item[ this.relatedModel.prototype.idAttribute ];
var model = Backbone.Relational.store.find( this.relatedModel, id );
if ( model && _.isObject( item ) ) {
model.set( item, options );
}
else if ( !model ) {
model = this.createModel( item );
}
if ( model && !this.related.getByCid( model ) && !this.related.get( model ) ) {
this.related._add( model );
}
}, this);
}
},
/**
* 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;
// Notify old 'related' object of the terminated relation
_.each( this.getReverseRelations(), function( relation ) {
relation.removeRelated( this.instance, options );
}, this );
// 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.
else {
var coll = this.related instanceof Backbone.Collection ? this.related : new this.collectionType();
this.setRelated( this.prepareCollection( coll ) );
this.findRelated( options );
}
// Notify new 'related' object of the new relation
_.each( this.getReverseRelations(), function( relation ) {
relation.addRelated( this.instance, options );
}, this );
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 = _.isString( item ) || _.isNumber( item ) ? item : item[ this.relatedModel.prototype.idAttribute ];
return 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
if( !(model instanceof Backbone.Model) ) return;
options = this.sanitizeOptions( options );
var dit = this;
_.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)
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);
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 );
});
},
addRelated: function( model, options ) {
var dit = this;
model.queue( function() { // Queued to avoid errors for adding 'model' to the 'this.related' set twice
if ( dit.related && !dit.related.getByCid( model ) && !dit.related.get( model ) ) {
dit.related._add( model, options );
}
});
},
removeRelated: function( model, options ) {
if ( this.related.getByCid( model ) || this.related.get( model ) ) {
this.related.remove( model, options );
}
}
});
/**
* New events:
* - 'add:<key>' (model, related collection, options)
* - 'remove:<key>' (model, related collection, options)
* - 'update:<key>' (model, related model or collection, options)
*/
Backbone.RelationalModel = Backbone.Model.extend({
relations: null, // Relation descriptions on the prototype
_relations: null, // Relation instances
_isInitialized: false,
_deferProcessing: false,
_queue: null,
constructor: function( attributes, options ) {
// Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'.
// Defer 'processQueue', so that when 'Relation.createModels' is used we:
// a) Survive 'Backbone.Collection._add'; this takes care we won't error on "can't add model to a set twice"
// (by creating a model from properties, having the model add itself to the collection via one of
// it's relations, then trying to add it to the collection).
// b) Trigger 'HasMany' collection events only after the model is really fully set up.
// Example that triggers both a and b: "p.get('jobs').add( { company: c, person: p } )".
var dit = this;
if ( options && options.collection ) {
this._deferProcessing = true;
var processQueue = function( model, coll ) {
if ( model === dit ) {
dit._deferProcessing = false;
dit.processQueue();
options.collection.unbind( 'relational:add', processQueue );
}
};
options.collection.bind( 'relational:add', processQueue );
// So we do process the queue eventually, regardless of whether this model really gets added to 'options.collection'.
_.defer( function() {
processQueue( dit );
});
}
this._queue = new Backbone.BlockingQueue();
this._queue.block();
Backbone.Relational.eventQueue.block();
Backbone.Model.prototype.constructor.apply( this, arguments );
// Try to run the global queue holding external events
Backbone.Relational.eventQueue.unblock();
},
/**
* Override 'trigger' to queue 'change' and 'change:*' events
*/
trigger: function( eventName ) {
if ( eventName.length > 5 && 'change' === eventName.substr( 0, 6 ) ) {
var dit = this, args = arguments;
Backbone.Relational.eventQueue.add( function() {
Backbone.Model.prototype.trigger.apply( dit, args );
});
}
else {
Backbone.Model.prototype.trigger.apply( this, arguments );
}
return this;
},
/**
* Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
* Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
*/
initializeRelations: function() {
this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
this._relations = [];
_.each( this.relations, function( rel ) {
var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type );
if ( type && type.prototype instanceof Backbone.Relation.prototype.constructor ) {
new type( this, rel ); // Also pushes the new Relation into _relations
}
else {
console && console.warn( 'Relation=%o; missing or invalid type!', rel );
}
}, this );
this._isInitialized = true;
this.release();
this.processQueue();
},
/**
* When new values are set, notify this model's relations (also if options.silent is set).
* (Relation.setRelated locks this model before calling 'set' on it to prevent loops)
*/
updateRelations: function( options ) {
if( this._isInitialized && !this.isLocked() ) {
_.each( this._relations, function( rel ) {
var val = this.attributes[ rel.key ];
if ( rel.related !== val ) {
this.trigger('relational:change:' + rel.key, this, val, options || {} );
}
}, this );
}
},
/**
* Either add to the queue (if we're not initialized yet), or execute right away.
*/
queue: function( func ) {
this._queue.add( func );
},
/**
* Process _queue
*/
processQueue: function() {
if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) {
this._queue.unblock();
}
},
/**
* Get a specific relation.
* @param key {string} The relation key to look for.
* @return {Backbone.Relation|null} An instance of 'Backbone.Relation', if a relation was found for 'key', or null.
*/
getRelation: function( key ) {
return _.detect( this._relations, function( rel ) {
if ( rel.key === key ) {
return true;
}
}, this );
},
/**
* Get all of the created relations.
* @return {array of Backbone.Relation}
*/
getRelations: function() {
return this._relations;
},
/**
* Retrieve related objects.
* @param key {string} The relation key to fetch models for.
* @param options {object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
* @return {xhr} An array of request objects
*/
fetchRelated: function( key, options ) {
options || ( options = {} );
var rel = this.getRelation( key ),
keyContents = rel && rel.keyContents,
toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
var id = _.isString( item ) || _.isNumber( item ) ? item : item[ rel.relatedModel.prototype.idAttribute ];
return id && !Backbone.Relational.store.find( rel.relatedModel, id );
}, this );
if ( toFetch && toFetch.length ) {
// Create a model for each entry in 'keyContents' that is to be fetched
var models = _.map( toFetch, function( item ) {
if ( typeof( item ) === 'object' ) {
var model = new rel.relatedModel( item );
}
else {
var attrs = {};
attrs[ rel.relatedModel.prototype.idAttribute ] = item;
var model = new rel.relatedModel( attrs );
}
return model;
}, this );
// Try if the 'collection' can provide a url to fetch a set of models in one request.
if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
var setUrl = rel.related.url( models );
}
// An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
// To make sure it can, test if the url we got by supplying a list of models to fetch is different from
// the one supplied for the default fetch action (without args to 'url').
if ( setUrl && setUrl !== rel.related.url() ) {
var opts = _.defaults( {
error: function() {
var args = arguments;
_.each( models, function( model ) {
model.destroy();
options.error && options.error.apply( model, args );
})
},
url: setUrl
},
options,
{ add: true }
);
var requests = [ rel.related.fetch( opts ) ];
}
else {
var requests = _.map( models, function( model ) {
var opts = _.defaults( {
error: function() {
model.destroy();
options.error && options.error.apply( model, arguments );
}
},
options
);
return model.fetch( opts );
}, this );
}
}
return _.isUndefined( requests ) ? [] : requests;
},
set: function( attributes, options ) {
Backbone.Relational.eventQueue.block();
var result = Backbone.Model.prototype.set.apply( this, arguments );
// 'set' is called quite late in 'Backbone.Model.prototype.constructor', but before 'initialize'.
// Ideal place to set up relations :)
if ( !this._isInitialized && !this.isLocked() ) {
Backbone.Relational.store.register( this );
this.initializeRelations();
}
// Update the 'idAttribute' in Backbone.store if; we don't want it to miss an 'id' update due to {silent:true}
else if ( attributes && this.idAttribute in attributes ) {
Backbone.Relational.store.update( this );
}
this.updateRelations( options );
// Try to run the global queue holding external events
Backbone.Relational.eventQueue.unblock();
return result;
},
unset: function( attributes, options ) {
Backbone.Relational.eventQueue.block();
var result = Backbone.Model.prototype.unset.apply( this, arguments );
this.updateRelations( options );