-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbackbone.JJRelational.js
1642 lines (1579 loc) · 58.8 KB
/
backbone.JJRelational.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
// Generated by CoffeeScript 1.9.3
/**
* Backbone JJRelational
* v0.2.13
*
* A relational plugin for Backbone JS that provides one-to-one, one-to-many and many-to-many relations between Backbone models.
*
* Tested with Backbone v1.0.0 and Underscore v.1.5.0
*
*/
(function() {
(function() {
"use strict";
var Backbone, _, exports, flatten, getUrlForIdQueue, getUrlForModelWithId, getValue, isManyType, isOneType, that, urlError, wrapError;
if (typeof window === 'undefined') {
_ = require('underscore');
Backbone = require('backbone');
exports = Backbone;
typeof module === 'undefined' || (module.exports = exports);
} else {
_ = window._;
Backbone = window.Backbone;
exports = window;
}
that = this;
/**
*
* The Store - well, stores all models in it.
* On creation, a model registers itself in the store by its `storeIdentifier`-attribute.
* Backbone JJStore provides some methods to get models by id/cid, for example, etc.
*
*/
Backbone.JJStore = {};
Backbone.JJStore._modelScopes = [exports];
Backbone.JJStore.Models = {};
Backbone.JJStore.Events = _.extend({}, Backbone.Events);
/**
* Adds a store for the given `storeIdentifier` if one doesn't exist yet.
* @param {String} storeIdentifier
* @return {Backbone.Collection} The matching store array
*/
Backbone.JJStore.__registerModelType = function(storeIdentifier) {
if (!this.Models[storeIdentifier]) {
this.Models[storeIdentifier] = new Backbone.Collection();
}
return this.Models[storeIdentifier];
};
/**
* Adds a model to its store if it's not present yet.
* @param {Backbone.JJRelationalModel} model The model to register
* @return {Boolean} true
*/
Backbone.JJStore.__registerModelInStore = function(model) {
var originalCollection, store;
originalCollection = model.collection;
store = this.__registerModelType(model.storeIdentifier);
if (!store.get(model)) {
store.add(model, {
silent: true
});
model.collection = originalCollection;
Backbone.JJStore.Events.trigger('added:' + model.storeIdentifier, model);
}
return true;
};
/**
* Removes a model from its store if present.
* @param {Backbone.JJRelationalModel} model The model to remove
* @return {Boolean} true
*/
Backbone.JJStore.__removeModelFromStore = function(model) {
this.Models[model.storeIdentifier].remove(model);
return true;
};
Backbone.JJStore._byId = function(store, id) {
if (_.isString(store)) {
store = this.Models[store];
}
if (store) {
return store.get(id);
}
return null;
};
/**
* Adds a scope for `getObjectByName` to look for model types by name.
* @param {Object} scope
*/
Backbone.JJStore.addModelScope = function(scope) {
return this._modelScopes.push(scope);
};
/**
* Removes a model scope
* @param {Object} scope
*/
Backbone.JJStore.removeModelScope = function(scope) {
return this._modelScopes = _.without(this._modelScopes, scope);
};
/**
*
* The main part
*
*/
Backbone.JJRelational = {};
Backbone.JJRelational.VERSION = '0.2.13';
Backbone.JJRelational.Config = {
url_id_appendix: '?ids=',
work_with_store: true
};
Backbone.JJRelational.CollectionTypes = {};
/**
* Find a model type on one of the modelScopes by name. Names are split on dots.
* @param {String} name
* @return {mixed}
*/
Backbone.JJRelational.__getObjectByName = function(name) {
var parts, type;
parts = name.split('.');
type = null;
_.find(Backbone.JJStore._modelScopes, function(scope) {
type = _.reduce(parts || [], function(memo, val) {
if (memo) {
return memo[val];
} else {
return void 0;
}
}, scope);
if (type && type !== scope) {
return true;
}
}, this);
return type;
};
/**
* Registers one or many collection-types, in order to build a correct collection instance for many-relations.
* @param {Object} collTypes key => value pairs, where `key` is the name under which to store the collection type (`value`)
* @return {Boolean} Success or not.
*/
Backbone.JJRelational.registerCollectionTypes = function(collTypes) {
var collection, name;
if (!_.isObject(collTypes)) {
return false;
}
for (name in collTypes) {
collection = collTypes[name];
Backbone.JJRelational.CollectionTypes[name] = collection;
}
return true;
};
/**
* Returns a collection type by the registered name.
* If none is found, Backbone.Collection will be returned.
* @param {String} name Name under which the collection type is stored
* @return {Backbone.Collection} Found collection type or Backbone.Collection
*/
Backbone.JJRelational.__getCollectionType = function(name) {
var coll, n, ref;
ref = Backbone.JJRelational.CollectionTypes;
for (n in ref) {
coll = ref[n];
if (n === name) {
return coll;
}
}
return Backbone.Collection;
};
/**
* Backbone.JJRelationalModel
*
* The main model extension of Backbone.Model
* Here come the good parts. :)
* @type {Backbone.JJRelationalModel}
*
*/
Backbone.Model.prototype.__save = Backbone.Model.prototype.save;
Backbone.JJRelationalModel = Backbone.Model.extend({
relationsInstalled: false,
/**
* The constructor:
* The Model is built normally, then the relational attributes are set up and the model is registered in the store.
* After that, the relational attributes are populated (if present in argument `attributes`).
* At last, the creation of the model is triggered on Backbone.JJStore.Events. (e.g. 'created:MyModel')
*
* @param {Object} attributes Initial attributes.
* @param {Object} options Options object.
* @return {Backbone.JJRelationalModel} The freshly created model.
*/
constructor: function(attributes, options) {
var existModel, id;
if (Backbone.JJRelational.Config.work_with_store && _.isObject(attributes) && (id = attributes[this.idAttribute])) {
existModel = Backbone.JJStore._byId(this.storeIdentifier, id);
}
if (existModel) {
existModel.set(attributes, options);
return existModel;
}
Backbone.Model.apply(this, arguments);
if (options && options.parse) {
attributes = this.parse(attributes || {}, options);
}
this.__prepopulate_rel_atts();
Backbone.JJStore.__registerModelInStore(this);
this.__populate_rels_with_atts(attributes, options);
Backbone.JJStore.Events.trigger('created:' + this.storeIdentifier, this);
this.trigger('relationsInstalled');
return this;
},
/**
* Initializes the relational attributes and binds basic listeners.
* has_many and many_many get empty collections, with a `_relational`-property containing:
* `owner`, `ownerKey`, `reverseKey` and `idQueue`
*
* @return {Backbone.JJRelationalModel}
*/
__prepopulate_rel_atts: function() {
var collType, gObj, i, indexOfID, j, len, ref, relModel, relation, value;
if (this.relations) {
ref = this.relations;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
relation = ref[i];
relModel = relation.relatedModel;
relation.includeInJSON = relation.includeInJSON ? relation.includeInJSON : [];
relation.includeInJSON = _.isArray(relation.includeInJSON) ? relation.includeInJSON : [relation.includeInJSON];
indexOfID = _.indexOf(relation.includeInJSON, 'id');
if (indexOfID >= 0 && this.idAttribute) {
relation.includeInJSON[indexOfID] = this.idAttribute;
}
if (relModel === void 0 || relModel.prototype instanceof Backbone.JJRelationalModel === false) {
if (_.isString(relModel)) {
gObj = Backbone.JJRelational.__getObjectByName(relModel);
if (gObj && gObj.prototype instanceof Backbone.JJRelationalModel === true) {
relModel = this.relations[i].relatedModel = gObj;
} else {
throw new TypeError('relatedModel "' + relModel + '" is neither a reference to a JJRelationalModel nor a string referring to an object in the global oject');
}
} else if (_.isFunction(relModel)) {
relModel = this.relations[i].relatedModel = relModel.call(this);
}
}
value;
if (relation && !isOneType(relation) && (collType = Backbone.JJRelational.__getCollectionType(relation.collectionType))) {
value = new collType();
value._relational = {
owner: this,
ownerKey: relation.key,
reverseKey: relation.reverseKey,
polymorphic: !!relation.polymorphic,
idQueue: []
};
} else {
value = null;
}
this.attributes[relation.key] = value;
Backbone.JJStore.Events.bind('created:' + relModel.prototype.storeIdentifier, this.newModelInStore, this);
}
this.bind('destroy', this._destroyAllRelations);
}
this.relationsInstalled = true;
return this;
},
/*
* Fills in any relational values that are present in the `attributes`-argument
* e.g. var m = new MyModel({ HasOneRelation : relationalModel });
*
* @param {Object} attributes
* @param {Object} options
*
*/
__populate_rels_with_atts: function(attributes, options) {
var j, key, len, relation, v, value;
for (key in attributes) {
value = attributes[key];
if (relation = this.getRelationByKey(key)) {
if (value instanceof Backbone.Collection === true) {
throw new TypeError('The attribute "' + key + '" is a collection. You should not replace whole collections in a relational attribute. Please use the direct reference to the model array (Backbone.Collection.models)');
} else {
value = _.isArray(value) ? value : [value];
for (j = 0, len = value.length; j < len; j++) {
v = value[j];
this.checkAndAdd(v, relation, options);
}
}
}
}
return this;
},
/**
* Override "`save`" method.
* The concept is: When saving a model, it is checked whether it has any relations containing a
* new model. If yes, the new model is saved first. When all new models have been saved, only
* then is the actual model saved.
* Relational collections are saved as an array of models + idQueue
* Concerning relations, the `includeInJSON`-property is used to generate the JSON object
*
* @param {String | Object} key See Backbone core
* @param {mixed | Object} value See Backbone core
* @param {Object} options (optional) See Backbone core
* @return {Backbone.$.ajax}
*/
save: function(key, value, options) {
attrs;
var actualSave, attributes, attrs, checkAndContinue, checkIfNew, j, k, l, len, len1, len2, len3, model, o, obj, opts, origOptions, ref, ref1, ref2, relModelsToSaveAfter, relModelsToSaveBefore, relation, returnXhr, reverseRelation, val;
returnXhr = null;
attributes = this.attributes;
if (_.isObject(key) || !key) {
attrs = key;
options = value;
} else if (key !== null) {
attrs = {};
attrs[key] = value;
}
options = options ? _.clone(options) : {};
options.isSave = true;
if (attrs && (!options || !options.wait) && !this.set(attrs, options)) {
return false;
}
options = _.extend({
validate: true
}, options);
if (!this._validate(attrs, options)) {
return false;
}
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
origOptions = _.clone(options);
relModelsToSaveAfter = [];
relModelsToSaveBefore = [];
actualSave = (function(_this) {
return function() {
var afterSuccess, generateSuccessHandler, j, latestSuccess, len, method, relModel, success, xhr;
success = options.success;
if (!options.contentType) {
options.contentType = 'application/json';
}
if (!options.data) {
options.data = JSON.stringify(_this.toJSON(_.extend({}, options, {
isSave: true
})));
}
if (options.parse === void 0) {
options.parse = true;
}
afterSuccess = new Backbone.$.Deferred();
latestSuccess = afterSuccess;
generateSuccessHandler = function(model) {
return function() {
var d, e, modelHasUrlError;
modelHasUrlError = false;
try {
_.result(model, 'url');
} catch (_error) {
e = _error;
modelHasUrlError = true;
}
if (!modelHasUrlError && model.isNew() && _.result(model, 'url')) {
return model.save({}, _.extend({}, origOptions));
} else {
d = new Backbone.$.Deferred();
d.resolve();
return d;
}
};
};
for (j = 0, len = relModelsToSaveAfter.length; j < len; j++) {
relModel = relModelsToSaveAfter[j];
latestSuccess = latestSuccess.then(generateSuccessHandler(relModel));
}
options.success = function(resp, status, xhr) {
var serverAttrs;
_this.attributes = attributes;
serverAttrs = _this.parse(resp, options);
if (options.wait) {
serverAttrs = _.extend(attrs || {}, serverAttrs);
}
if (_.isObject(serverAttrs) && !_this.set(serverAttrs, options)) {
return false;
}
if (success) {
success(_this, resp, options);
}
afterSuccess.resolve();
return _this.trigger('sync', _this, resp, options);
};
wrapError(_this, options);
method = _this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') {
options.attrs = attrs;
delete options.data;
}
xhr = _this.sync(method, _this, options);
if (attrs && options.wait) {
_this.attributes = attributes;
}
return latestSuccess;
};
})(this);
if (!options.ignoreSaveOnModels) {
options.ignoreSaveOnModels = [this];
}
checkIfNew = function(val, saveAfter) {
try {
if (val && (val instanceof Backbone.JJRelationalModel) && val.url() && val.isNew()) {
if (saveAfter) {
return relModelsToSaveAfter.push(model);
} else {
return relModelsToSaveBefore.push({
model: val,
done: false
});
}
}
} catch (_error) {}
};
checkAndContinue = function() {
var done, j, len, obj;
if (_.isEmpty(relModelsToSaveBefore)) {
returnXhr = actualSave();
}
done = true;
for (j = 0, len = relModelsToSaveBefore.length; j < len; j++) {
obj = relModelsToSaveBefore[j];
if (obj.done === false) {
done = false;
}
}
if (done) {
return returnXhr = actualSave();
}
};
if (this.relations) {
ref = this.relations;
for (j = 0, len = ref.length; j < len; j++) {
relation = ref[j];
val = this.get(relation.key);
reverseRelation = val instanceof Backbone.Collection && val.first() ? _.findWhere(val.first().relations, {
key: relation.reverseKey
}) : null;
if (reverseRelation && isManyType(relation) && isOneType(reverseRelation)) {
ref1 = val.models;
for (k = 0, len1 = ref1.length; k < len1; k++) {
model = ref1[k];
checkIfNew(model, true);
}
} else if (isManyType(relation)) {
ref2 = val.models;
for (l = 0, len2 = ref2.length; l < len2; l++) {
model = ref2[l];
checkIfNew(model, false);
}
} else if (isOneType(relation)) {
checkIfNew(val, false);
}
}
}
if (_.isEmpty(relModelsToSaveBefore)) {
returnXhr = actualSave();
}
for (o = 0, len3 = relModelsToSaveBefore.length; o < len3; o++) {
obj = relModelsToSaveBefore[o];
if (_.indexOf(options.ignoreSaveOnModels, obj.model) <= -1) {
options.ignoreSaveOnModels.push(obj.model);
opts = _.clone(options);
opts.success = function(model, resp) {
var len4, p;
for (p = 0, len4 = relModelsToSaveBefore.length; p < len4; p++) {
obj = relModelsToSaveBefore[p];
if (obj.model.cid === model.cid) {
obj.done = true;
}
}
Backbone.JJStore.Events.trigger('created:' + model.storeIdentifier, model);
return checkAndContinue();
};
obj.model.save({}, opts);
} else {
obj.done = true;
checkAndContinue();
}
}
return returnXhr;
},
/**
* Override "`set`" method.
* This is pretty much the most important override...
* It's almost exactly the same as the core `set` except for one small code block handling relations.
* See `@begin & @end edit` in the comments
*
* If `set` is the heart of the beast in Backbone, JJRelational makes sure it's not made of stone.
*
* @param {String | Object} key See Backbone core
* @param {mixed | Object} val See Backbone core
* @param {Object} options (optional) Backbone core
*/
set: function(key, val, options) {
var attrs, changes, changing, checkAndSet, current, i, prev, silent, triggerChanges, unset, value;
if (key === null) {
return this;
}
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
attrs = {};
attrs[key] = val;
}
options = options || {};
if (!this._validate(attrs, options)) {
return false;
}
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes;
prev = this._previousAttributes;
checkAndSet = (function(_this) {
return function(key, value) {
var currValue, isRelation, j, len, relation, shouldRefreshRelation, v;
if (!_.contains(_.pluck(_this.relations, 'key'), key)) {
if (!_.isEqual(current[key], value)) {
changes.push(key);
}
if (!_.isEqual(prev[key], value)) {
_this.changed[key] = value;
} else {
delete _this.changed[key];
}
}
/**
* @begin edit JJRelational
*/
relation = _this.getRelationByKey(key);
isRelation = _this.relationsInstalled && relation;
currValue = _this.get(key);
shouldRefreshRelation = isRelation && (unset || (currValue === null) || (_.isNumber(currValue) && _.isNumber(value) && currValue !== value) || (!_.isObject(value) && _.isObject(currValue) && currValue.id && currValue.id !== value) || (_.isObject(value) && _.isObject(currValue) && currValue.id && value.id && currValue.id !== value.id) || (value instanceof Backbone.Model && value.cid !== currValue.cid) || (_.isArray(value) && (!_.isEqual(value, currValue) || currValue instanceof Backbone.Collection)));
if (shouldRefreshRelation) {
changes.push(key);
_this.changed[key] = value;
value = _.isArray(value) ? value : [value];
if (currValue instanceof Backbone.Collection) {
currValue.set(value, options);
} else {
_this._emptyRelation(relation);
for (j = 0, len = value.length; j < len; j++) {
v = value[j];
if (!unset) {
_this.checkAndAdd(v, relation, options);
}
}
}
} else if (!isRelation) {
if (unset) {
delete current[key];
} else {
current[key] = value;
}
}
return _this;
/**
* @end edit JJRelational
*/
};
})(this);
triggerChanges = (function(_this) {
return function() {
var change, j, len, results;
if (!silent) {
if (changes.length) {
_this._pending = true;
}
results = [];
for (j = 0, len = changes.length; j < len; j++) {
change = changes[j];
results.push(_this.trigger('change:' + change, _this, current[change], options));
}
return results;
}
};
})(this);
if (this.idAttribute in attrs) {
this.id = attrs[this.idAttribute];
checkAndSet(this.idAttribute, attrs[this.idAttribute]);
triggerChanges();
i = _.indexOf(changes, this.idAttribute);
if (~i) {
changes.splice(i, 1);
}
delete attrs[this.idAttribute];
}
if (this.idAttribute in attrs) {
this.id = attrs[this.idAttribute];
}
for (key in attrs) {
value = attrs[key];
checkAndSet(key, value);
}
triggerChanges();
if (changing) {
return this;
}
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
/**
* Override "`_validate`" method.
* The difference is that it flattens relational collections down to its model array.
*
* @param {Object} attrs see Backbone core
* @param {Object} options see Backbone core
* @return {Boolean} see Backbone core
*/
_validate: function(attrs, options) {
var error, j, len, ref, relation, val;
if (!options.validate || !this.validate) {
return true;
}
attrs = _.extend({}, this.attributes, attrs);
ref = this.relations;
for (j = 0, len = ref.length; j < len; j++) {
relation = ref[j];
val = attrs[relation.key];
if (val instanceof Backbone.Collection === true) {
attrs[relation.key] = val.models;
}
}
error = this.validationError = this.validate(attrs, options) || null;
if (!error) {
return true;
}
this.trigger('invalid', this, error, _.extend(options || {}, {
validationError: error
}));
return false;
},
/**
* Override `toJSON` method for relation handling.
* If it's for saving (`options.isSave == true`), then it uses the includeInJSON property of relations.
* This can go down as many levels as required.
* If not, it just goes down one level.
*
* @param {Object} options Options object
* @return {Object} Final JSON object
*/
toJSON: function(options) {
var include, j, json, k, key, len, len1, ref, ref1, relValue, relation;
options = options || {};
if (options.withRelIDs) {
return this.toJSONWithRelIDs(options);
}
json = _.clone(this.attributes);
if (options.bypass) {
return json;
}
if (options.isSave) {
ref = this.relations;
for (j = 0, len = ref.length; j < len; j++) {
relation = ref[j];
if (options.scaffold && (_.indexOf(options.scaffold, relation.key) < 0)) {
continue;
}
include = relation.includeInJSON;
key = relation.key;
relValue = this.get(key);
if (isOneType(relation)) {
if (relValue) {
if (relValue instanceof relation.relatedModel === true) {
if (include.length === 0) {
json[relation.key] = relValue.toJSONWithRelIDs(options);
} else if (include.length === 1) {
json[relation.key] = relValue.get(include[0]);
} else {
json[relation.key] = relValue.toJSON(_.extend({}, options, {
isSave: true,
scaffold: include
}));
}
} else {
json[relation.key] = _.indexOf(include, relation.relatedModel.prototype.idAttribute) >= 0 ? relValue : null;
}
} else {
json[relation.key] = null;
}
} else if (isManyType(relation)) {
if (include.length === 0) {
json[relation.key] = relValue.toJSON(_.extend({}, options, {
withRelIDs: true
}));
} else if (include.length === 1) {
json[relation.key] = relValue.getArrayForAttribute(include[0]);
} else {
json[relation.key] = relValue.toJSON(_.extend({}, options, {
isSave: true,
scaffold: include
}));
if (_.indexOf(include, 'id') >= 0) {
json[relation.key].push(relValue._relational.idQueue);
}
}
}
}
} else {
ref1 = this.relations;
for (k = 0, len1 = ref1.length; k < len1; k++) {
relation = ref1[k];
relValue = this.get(relation.key);
if (isOneType(relation)) {
json[relation.key] = relValue instanceof relation.relatedModel === true ? relValue.toJSONWithRelIDs(options) : relValue;
} else if (isManyType(relation)) {
json[relation.key] = relValue.toJSON(_.extend({}, options, {
withRelIDs: true
}));
}
}
}
if (options.scaffold) {
json = _.pick.apply(that, [json, options.scaffold]);
}
return json;
},
/**
* Returns a JSON of the model with the relations represented only by ids.
*
* @return {Object} Final JSON object
*/
toJSONWithRelIDs: function() {
var j, json, len, ref, relValue, relation;
json = _.clone(this.attributes);
ref = this.relations;
for (j = 0, len = ref.length; j < len; j++) {
relation = ref[j];
relValue = this.get(relation.key);
if (isOneType(relation)) {
json[relation.key] = relValue instanceof relation.relatedModel === true ? relValue.id : relValue;
} else if (isManyType(relation)) {
json[relation.key] = relValue.getIDArray();
}
}
return json;
},
/**
* This function checks a given value and adds it to the relation accordingly.
* If it's a model, it adds it to the relation. If it's a set of attributes, it creates a new model
* and adds it. Otherwise it assumes that it must be the id, looks it up in the store (if there's
* already a model) or adds it to the relation's idQueue.
*
* @param {mixed} val The value to check
* @param {Object} rel The relation which to add the value to
* @param {Object} options Options object
* @return {Backbone.JJRelationalModel}
*/
checkAndAdd: function(val, rel, options) {
var existModel, newModel, relModel, storeIdentifier;
options = options || {};
relModel = rel.relatedModel;
if (val instanceof relModel === true) {
this.addToRelation(val, rel, false);
} else if (_.isObject(val) && val instanceof Backbone.Model === false) {
if (this.relationsInstalled && (val[rel.reverseKey] == null)) {
val[rel.reverseKey] = this;
}
if (rel.polymorphic && rel.collectionType) {
newModel = new Backbone.JJRelational.CollectionTypes[rel.collectionType].prototype.model(val);
} else {
newModel = new relModel(val);
}
this.addToRelation(newModel, rel, false);
} else {
storeIdentifier = relModel.prototype.storeIdentifier;
if (existModel = Backbone.JJStore._byId(storeIdentifier, val)) {
if (options.ignoreModel === existModel) {
return;
}
this.addToRelation(existModel, rel, false);
} else if (isManyType(rel)) {
this.get(rel.key).addToIdQueue(val);
} else if (isOneType(rel)) {
this.setHasOneRelation(rel, val, true);
}
}
return this;
},
/**
* This function is triggered by a newly created model (@see Backbone.JJRelationalModel.constructor)
* that has been registered in the store and COULD belong to a relation.
*
* @param {Backbone.JJRelationalModel} model The newly created model which triggered the event.
*/
newModelInStore: function(model) {
var id, idQueue, relColl, relation;
id = model.id;
if (id) {
relation = this.getRelationByIdentifier(model.storeIdentifier);
if (relation) {
if (isOneType(relation)) {
if (id === this.get(relation.key)) {
this.addToRelation(model, relation, false);
}
} else if (isManyType(relation)) {
relColl = this.get(relation.key);
idQueue = relColl._relational.idQueue;
if (_.indexOf(idQueue, id) > -1) {
this.addToRelation(model, relation, false);
}
}
}
}
return void 0;
},
/**
* Adds a model to a relation.
*
* @param {Backbone.JJRelationalModel} model The model to add
* @param {String | Object} relation Relation object or relationKey
* @param {Boolean} silent Indicates whether to pass on the relation to the added model. (reverse set)
* @return {Backbone.JJRelationalModel}
*/
addToRelation: function(model, relation, silent) {
if (!_.isObject(relation)) {
relation = this.getRelationByKey(relation);
}
if (relation && (model instanceof relation.relatedModel === true)) {
if (isOneType(relation)) {
if (this.get(relation.key) !== model) {
this.setHasOneRelation(relation, model, silent);
}
} else if (isManyType(relation)) {
this.get(relation.key).add(model, {
silentRelation: silent
});
}
}
return this;
},
/**
* Sets a value on a has_one relation.
*
* @param {String | Object} relation Relation object or relationKey
* @param {mixed} val The value to set
* @param {Boolean} silentRelation Indicates whether to pass on the relation to the added model. (reverse set)
*/
setHasOneRelation: function(relation, val, silentRelation) {
var prev;
if (!_.isObject(relation)) {
relation = this.getRelationByKey(relation);
}
prev = this.get(relation.key);
this.attributes[relation.key] = val;
if (prev instanceof relation.relatedModel === true) {
prev.removeFromRelation(relation.reverseKey, this, true);
}
if (silentRelation) {
return;
}
if (val instanceof relation.relatedModel === true) {
val.addToRelation(this, relation.reverseKey, true);
}
return this;
},
/**
* Removes a model from a relation
* @param {String | Object} relation Relation object or relationKey
* @param {Backbone.JJRelationalModel} model The model to add
* @param {Boolean} silent Indicates whether to pass on the relation to the added model. (reverse set)
* @return {Backbone.JJRelationalModel}
*/
removeFromRelation: function(relation, model, silent) {
var coll;
if (!_.isObject(relation)) {
relation = this.getRelationByKey(relation);
}
if (relation) {
if (isOneType(relation)) {
this.setHasOneRelation(relation, null, silent);
} else if (isManyType(relation)) {
coll = this.get(relation.key);
if (model instanceof relation.relatedModel === true) {
coll.remove(model, {
silentRelation: silent
});
} else {
coll.removeFromIdQueue(model);
}
}
}
return this;
},
/**
* Completely empties a relation.
*
* @param {Object} relation
* @return {Backbone.JJRelationalModel}
*/
_emptyRelation: function(relation) {
var coll;
if (isOneType(relation)) {
this.setHasOneRelation(relation, null, false);
} else if (isManyType(relation)) {
coll = this.get(relation.key);
coll._cleanup();
}
return this;
},
/**
* Cleanup function that removes all listeners, empties relation and informs related models of removal
*
* @return {Backbone.JJRelationalModel}
*/
_destroyAllRelations: function() {
var j, len, ref, relModel, relation;
Backbone.JJStore.__removeModelFromStore(this);
ref = this.relations;
for (j = 0, len = ref.length; j < len; j++) {
relation = ref[j];
this.unbind('destroy', this._destroyAllRelations);
Backbone.JJStore.Events.unbind('created:' + relation.relatedModel.prototype.storeIdentifier, this.newModelInStore, this);
if (isOneType(relation) && (relModel = this.get(relation.key))) {
this.setHasOneRelation(relation, null, false);
} else if (isManyType(relation)) {
this.get(relation.key)._cleanup();
}
}
return this;
},
/**
* Helper function to get the length of the relational idQueue (for has_one: 0 || 1)
*
* @param {String | Object} relation Relation object or relationKey
* @return {Integer} Length of idQueue
*/
getIdQueueLength: function(relation) {
var val;
if (!_.isObject(relation)) {
relation = this.getRelationByKey(relation);
}
if (relation) {
if (isOneType(relation)) {
val = this.get(relation.key);
if ((!val) || (val instanceof relation.relatedModel === true)) {
return 0;
} else {
return 1;
}
} else if (isManyType(relation)) {
return this.get(relation.key)._relational.idQueue.length;
}
}
return 0;
},
/**
* Clears the idQueue of a relation
*
* @param {String | Object} relation Relation object or relationKey
* @return {Backbone.JJRelationalModel}
*/
clearIdQueue: function(relation) {
var coll, val;