-
Notifications
You must be signed in to change notification settings - Fork 20
/
FormModel.js
1126 lines (1064 loc) · 44.3 KB
/
FormModel.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
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone', './NestedModel', './validation'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'), require('./NestedModel'), require('./validation'));
} else {
root.Torso = root.Torso || {};
root.Torso.FormModel = factory(root._, root.Backbone, root.Torso.NestedModel, root.Torso.validation);
}
}(this, function(_, Backbone, NestedModel, validation) {
'use strict';
var $ = Backbone.$;
/**
* Generic Form Model
*
* @class FormModel
* @extends NestedModel
* @mixes validationMixin
*
* @author kent.willis@vecna.com
*
* @see <a href="../annotated/modules/FormModel.html">FormModel Annotated Source</a>
*/
var FormModel = NestedModel.extend(/** @lends FormModel# */{
/**
* @private
* @property __currentMappings
* @type Object
*/
/**
* @private
* @property __cache
* @type Object
*/
/**
* @private
* @property __currentObjectModels
* @type Object
*/
/**
* @private
* @property __currentUpdateEvents
* @type Array
*/
/**
* @property validation
* @type Object
*/
/**
* @property labels
* @type Object
*/
/**
* Map from aliases (either model names or computed value names) to mappings.
* Please refer to the documentation on the constructor about the form and options for this field.
* @property mapping
* @type Object
*/
mapping: undefined,
/**
* Map from model aliases to model instances.
* Please refer to the documentation on the constructor about the form and options for this field.
* @property models
* @type Object
*/
models: undefined,
/**
* Constructor the form model. Can take in attributes to set initially. These will override any pulled values from object models
* on initialization. On initialization the object model's values will be pulled once.
* For the options, here are needed definitions:
* mapping: {
* modelName: 'foo bar baz' // track a model by providing an alias for a name and a space seperated list of fields to track as a String
* modelName2: true // to track all fields
* ... // can have many model mappings
* computedName: {
* modelName: 'taz raz', // mappings for models that will be used for this computed mapping.
* ... // can have many model mappings for a computed
* pull: function(models) {}, // a callback that will be invoked when pulling data from the Object model. Passes in a map of model alias/name to shallow copies of fields being tracked on that model.
* push: function(models) {} // a callback that will be invoked when pushing data to the Object model. Passes in a map of model alias/name to object model being tracked under that alias.
* }
* },
* models: {
* modelName: modelInstance, // optionally, provide a set of model instance to model name (aliases) to start tracking
* modelName2: modelInstance2 // provide as many aliases to model instances as you'd like
* }
* @param {Object} [options]
* @param {Object} [options.mapping] map from aliases (either model names or computed value names) to mappings.
* A model mapping can bind an alias to a space seperated list of fields to track as a String r the boolean true if it is mapping all the
* fields. A computed mapping can bind an alias to a set of model mappings required for this computed value and both a pull and/or push method
* that are used to compute different values to or from object model(s).
* @param {Object} [options.models] Because the options.mapping parameter only allows you to define the mappings to aliases, this options allows
* you to bind model instances to aliases. Setting model instances to aliases are required to actually begin pulling/pushing values.
* @param {boolean} [options.startUpdating=false] set to true if you want to immediately set up listeners to update this form
* model as the object model updates. You can always toggle this state with startUpdating() and stopUpdating().
* @param {Object} [options.validation] A Backbone.Validation plugin hash to dictate the validation rules
* @param {Object} [options.labels] A Backbone.Validation plugin hash to dictate the attribute labels
*/
constructor: function(attributes, options) {
options = options || {};
this.__cache = {};
this.__currentUpdateEvents = [];
this.__currentMappings = {};
this.__currentObjectModels = {};
// override + extend the validation and labels hashes
this.validation = _.extend({}, this.validation, options.validation);
this.labels = _.extend({}, this.labels, options.labels);
NestedModel.apply(this, arguments);
this.__initMappings(options);
// Do an initial pull
this.pull();
// The pull may have overridden default attributes
if (attributes) {
this.set(attributes);
}
// Begin updating if requested
if (options.startUpdating) {
this.startUpdating();
}
this.trigger('initialization-complete');
},
/**
* @param {string} alias the alias of the mapping - either a model mapping or a computed mapping
* @returns the mapping config for that alias
*/
getMapping: function(alias) {
return this.__currentMappings[alias];
},
/**
* @returns all the current mapping configs
*/
getMappings: function() {
return this.__currentMappings;
},
/**
* Define or redefine how the form model pull/pushes or otherwise tracks properties between an object model(s).
* Examples:
* this.setMapping('modelAlias', true, optional model instance);
* this.setMapping('modelAlias, 'foo bar baz', optional model instance);
* this.setMapping('computedAlias', {
* model1: 'foo',
* model2: 'bar',
* push: function(models) {
* models.model1.set('foo', this.get('foobar')[0]);
* models.model2.set('bar', this.get('foobar')[1]);
* },
* pull: function(models) {
* this.set('foobar', [models.model1.foo, models.model2.bar]);
* },
* }, optional model map)
* @param {string} alias the name for the mapping - either a model mapping or a computed mapping
* @param {(string|boolean|Object)} mapping Provides the mapping for this alias. If trying to map to a model, then either provide
* a space delimited list of fields to track as a String or the boolean true to track all the model's fields. If the mapping is for
* a computed value, then provide a map from model alias to model mapping for all the fields needed for the computed and a pull method
* if you want to change/combine/split object model properties before bringing them into the form model and a push method if you want to
* change/combine/split form model properties before pushing them to the object models.
* @param {Object|external:Backbone-Model} [models] Provides instances to use for this mapping. If mapping is a computed,
* provide a map from alias to model instance. If mapping is for a single model, just provide the model instance for that alias.
* @param [copy=false] if true, will pull values definined by this mapping after setting the mapping. Requires models to be passed in.
*/
setMapping: function(alias, mapping, models, copy) {
var computed, fields,
config = {};
if (_.isString(mapping)) {
fields = mapping.split(' ');
} else if (mapping === true) {
fields = undefined;
} else if (_.isObject(mapping)) {
mapping = _.clone(mapping);
computed = true;
}
config.computed = computed;
if (computed) {
config.mapping = mapping;
_.each(this.__getModelAliases(config), function(modelAlias) {
var configMappingForAlias = config.mapping[modelAlias];
if (_.isString(configMappingForAlias)) {
configMappingForAlias = configMappingForAlias.split(' ');
} else if (configMappingForAlias === true) {
configMappingForAlias = undefined;
}
config.mapping[modelAlias] = configMappingForAlias;
});
} else {
config.mapping = fields;
}
this.__currentMappings[alias] = config;
if (models) {
if (computed) {
this.trackModels(models, copy);
} else {
this.trackModel(alias, models, copy);
}
}
},
/**
* Sets multiple mappings (both model mappings and computed value mappings) with one call.
* Uses the same style of mapping syntax as the constructor. Please refer to the documentation on the constructor.
* Here is an example:
* this.setMappings({
* model1: 'foo bar',
* model2: 'baz',
* ssn: {
* model1: 'ssn',
* model2: 'lastssn'
* push: function(models) {},
* pull: function(models) {},
* }
* }, optional model map)
* @param {Object} mappings Uses the same style of mapping syntax as the constructor. Please refer to the documentation on the constructor.
* @param {Object} [models] this parameter allows you to immediately bind model instances to aliases. Keys are aliases and values are external:Backbone-Models.
* @param [copy=false] if true, will pull values definined by this mapping after setting the mapping. Requires models to be passed in.
*/
setMappings: function(mappings, models, copy) {
_.each(mappings, function(mapping, alias) {
this.setMapping(alias, mapping);
}, this);
if (models) {
this.trackModels(models, copy);
}
},
/**
* Remove a mapping (model or computed) by alias
* @param {string|external:Backbone-Model} aliasOrModel if a String is provided, it will unset the mapping with that alias.
* If a external:Backbone-Model is provided, it will remove the model mapping that was bound to that model.
* @param {boolean} [removeModelIfUntracked=false] If true, after the mapping is removed, the model will also be unset but only if
* no other mappings reference it. Note, setting this to true will not remove any computed mappings that also use that model.
*/
unsetMapping: function(aliasOrModel, removeModelIfUntracked) {
var alias = this.__findAlias(aliasOrModel);
if (alias) {
delete this.__currentMappings[alias];
}
var model = this.getTrackedModel(alias);
if (removeModelIfUntracked && model && _.isEmpty(this.__getTrackedModelFields(model))) {
this.untrackModel(model);
}
},
/**
* Removes all current mappings
* Does NOT remove current model being tracked. Call this.untrackModels afterwards if you wish this behavior.
*/
unsetMappings: function() {
this.__currentMappings = {};
this.resetUpdating();
},
/**
* Returns the object model currently bound to the given name/alias.
* @param {string} alias the name/alias used by the mappings.
* @returns {external:Backbone-Model} the model currently bound to the alias
*/
getTrackedModel: function(alias) {
return this.__currentObjectModels[alias];
},
/**
* Returns all the currently tracked object models
* @returns all the currently tracked object models
*/
getTrackedModels: function() {
return _.values(this.__currentObjectModels);
},
/**
* Use {@link FormModel#trackModel} instead.
* @see {@link FormModel#trackModel}
* @deprecated
*/
setTrackedModel: function() {
this.trackModel.apply(this, arguments);
},
/**
* Update or create a binding between an object model and an alias.
* @param {string} alias the alias/name to bind to.
* @param {external:Backbone-Model} model the model to be bound. Mappings referencing this alias will start applying to this model.
* @param {boolean} [copy=false] if true, the form model will perform a pull on any mappings using this alias.
*/
trackModel: function(alias, model, copy) {
this.__currentObjectModels[alias] = model;
this.__updateCache(model);
this.resetUpdating();
if (copy) {
_.each(this.getMappings(), function(config, mappingAlias) {
var modelAliases;
if (alias === mappingAlias) {
this.__pull(mappingAlias);
}
if (config.computed) {
modelAliases = this.__getModelAliases(mappingAlias);
if (_.contains(modelAliases, alias)) {
this.__pull(mappingAlias);
}
}
}, this);
}
},
/**
* Use {@link FormModel#trackModels} instead.
* @see {@link FormModel#trackModels}
* @deprecated
*/
setTrackedModels: function() {
this.trackModels.apply(this, arguments);
},
/**
* Binds multiple models to their aliases.
* @param {Object.<string, external:Backbone-Model>} models A map from alias/name to model to be bound to that alias.
* @param {boolean} [copy=false] if true, the form model will perform a pull on any mapping using these models.
*/
trackModels: function(models, copy) {
_.each(models, function(instance, alias) {
this.trackModel(alias, instance, copy);
}, this);
},
/**
* Use {@link FormModel#untrackModel} instead.
* @see {@link FormModel#untrackModel}
* @deprecated
*/
unsetTrackedModel: function() {
this.untrackModel.apply(this, arguments);
},
/**
* Removes the binding between a model alias and a model instance. Effectively stops tracking that model.
* @param {string|external:Backbone-Model} aliasOrModel If a string is given, it will unset the model using that alias. If a model instance
* is given, it will unbind whatever alias is currently bound to it.
*/
untrackModel: function(aliasOrModel) {
var model,
alias = this.__findAlias(aliasOrModel);
if (alias) {
model = this.__currentObjectModels[alias];
delete this.__currentObjectModels[alias];
this.__updateCache(model);
}
this.resetUpdating();
},
/**
* Use {@link FormModel#untrackModels} instead.
* @see {@link FormModel#untrackModels}
* @deprecated
*/
unsetTrackedModels: function() {
this.untrackModels.apply(this, arguments);
},
/**
* Removes all the bindings between model aliases and model instances. Effectively stops tracking the current models.
*/
untrackModels: function() {
this.__currentObjectModels = [];
this.__updateCache();
this.resetUpdating();
},
/**
* Pushes values from this form model back to the object models it is tracking. This includes invoking the push callbacks from
* computed values
*/
push: function() {
_.each(this.getMappings(), function(config, alias) {
this.__push(alias);
}, this);
},
/**
* Pulls the most recent values of every object model that this form model tracks including computed values
* NOTE: using this method can override user-submitted data from an HTML form. Use caution.
*/
pull: function() {
_.each(this.getMappings(), function(config, alias) {
this.__pull(alias);
}, this);
this.__updateCache();
},
/**
* If FormModel has a "url" property defined, it will invoke a save on the form model, and after successfully
* saving, will perform a push.
* If no "url" property is defined then the following behavior is used:
* Pushes the form model values to the object models it is tracking and invokes save on each one. Returns a promise.
* NOTE: if no url is specified and no models are being tracked, it will instead trigger a 'save-fail' event and reject the returned promise
* with a payload that mimics a server response: {none: { success: false, response: [{ responseJSON: { generalReasons: [{messageKey: 'no.models.were.bound.to.form'}] }}] }}
* @param {Object} [options]
* @param {boolean} [options.rollback=true] if true, when any object model fails to save, it will revert the object
* model attributes to the state they were before calling save. NOTE: if there are updates that happen
* to object models within the timing of this save method, the updates could be lost.
* @param {boolean} [options.force=true] if false, the form model will check to see if an update has been made
* to any object models it is tracking since it's last pull. If any stale data is found, save with throw an exception
* with attributes: {name: 'Stale data', staleModels: [Array of model cid's]}
* @returns when using a "url", a promise is returned for the save on this form model.
If not using a "url", a promise that will either resolve when all the models have successfully saved in which case the context returned
* is an array of the responses (order determined by first the array of models and then the array of models used by
* the computed values, normalized), or if any of the saves fail, the promise will be rejected with an array of responses.
* Note: the size of the failure array will always be one - the first model that failed. This is a side-effect of $.when
*/
save: function(options) {
var notTrackingResponse, url,
deferred = new $.Deferred(),
formModel = this;
options = options || {};
_.defaults(options, {
rollback: true,
force: true
});
try {
url = _.result(formModel, 'url');
} catch (e) {
// no url attached to this form model. Continue by pushing to models.
}
if (url) {
return NestedModel.prototype.save.apply(formModel, arguments).done(function() {
formModel.push();
});
} else if (this.isTrackingAnyObjectModel()) {
this.__saveToModels(deferred, options);
return deferred.promise();
} else {
// Return a response that is generated when this form model is not tracking an object model
notTrackingResponse = {
'none': {
success: false,
response: [{
responseJSON: {
generalReasons: [{messageKey: 'no.models.were.bound.to.form'}]
}
}]
}
};
this.trigger('save-fail', notTrackingResponse);
return (new $.Deferred()).reject(notTrackingResponse).promise();
}
},
/**
* @returns true if this form model is backed by an Object model. That means that at least one object model was bound to an mapping alias.
*/
isTrackingAnyObjectModel: function() {
return _.size(this.__currentObjectModels) > 0;
},
/**
* @returns true if any updates to an object model will immediately copy new values into this form model.
*/
isUpdating: function() {
return this.__currentUpdateEvents.length > 0;
},
/**
* Will add listeners that will automatically pull new updates from this form's object models.
* @param {boolean} [pullFirst=false] if true, the form model will pull most recent values then start listening
*/
startUpdating: function(pullFirst) {
if (this.isTrackingAnyObjectModel() && !this.isUpdating()) {
if (pullFirst) {
this.pull();
}
this.__setupListeners();
}
},
/**
* This will stop the form model from listening to its object models.
*/
stopUpdating: function() {
_.each(this.__currentUpdateEvents, function(eventConfig) {
this.stopListening(eventConfig.model, eventConfig.eventName);
}, this);
this.__currentUpdateEvents = [];
},
/**
* If updating, it will reset the updating events to match the current mappings.
*/
resetUpdating: function() {
if (this.isUpdating()) {
this.stopUpdating();
this.startUpdating();
}
},
/**
* @param {Backbone.Model} model the backbone model that is being checked
* @param {Object} [staleModels] a hash that will be updated to contain this model if it is stale in the form: cid -> model.
* @param {Object} [currentHashValues] If passed an object, it will look in this cache for the current value of the object model
* instead of calculating it. It should be key'ed by the model's cid
* @returns {boolean} true if the model passed in has been changed since the last pull from the object model.
*/
isModelStale: function(model, staleModels, currentHashValues) {
var hashValue;
currentHashValues = currentHashValues || {};
if (!currentHashValues[model.cid]) {
currentHashValues[model.cid] = this.__generateHashValue(model);
}
hashValue = currentHashValues[model.cid];
var isStaleModel = this.__cache[model.cid] !== hashValue;
if (staleModels) {
if (isStaleModel) {
staleModels[model.cid] = model;
} else if (staleModels[model.cid]) {
delete staleModels[model.cid];
}
}
return isStaleModel;
},
/**
* @returns {Array} an array of the object models that have been updated since the last pull from this form model
*/
checkIfModelsAreStale: function() {
var staleModels = {},
currentHashValues = this.__generateAllHashValues();
_.each(this.getTrackedModels(), function(model) {
this.isModelStale(model, staleModels, currentHashValues);
}, this);
return _.values(staleModels);
},
//************** Private methods **************//
/**
* Sets up a listener to update the form model if the model's field (or any field) changes.
* @param {Backbone.Model} model the object model from which this form model will start listen to changes
* @param {string} [field] the field name that it will start listening to. If no field is given, it will listen to the general 'change' event.
* @private
*/
__listenToModelField: function(model, field) {
var callback, eventName;
if (field) {
eventName = 'change:' + field;
callback = _.bind(this.__updateFormField, {
formModel: this,
field: field
});
} else {
eventName = 'change';
callback = this.__updateFormModel;
}
this.listenTo(model, eventName, callback);
this.__currentUpdateEvents.push({model: model, eventName: eventName});
},
/**
* Sets up a listener on one (or all) of the fields that is needed to update a computed value
* @param {Backbone.Model} model the object model from which this form model will start listen to changes
* @param {string} [field] the field name that it will start listening to. If no field is given, it will listen to the general 'change' event.
* @param {string} computedAlias the name/alias of the computed mapping being used.
* @private
*/
__listenToComputedValuesDependency: function(model, field, computedAlias) {
var callback, eventName;
if (field) {
eventName = 'change:' + field;
} else {
eventName = 'change';
}
callback = _.bind(this.__invokeComputedPull, {
formModel: this,
alias: computedAlias
});
this.listenTo(model, eventName, callback);
this.__currentUpdateEvents.push({model: model, eventName: eventName});
},
/**
* Returns the models that a currently being tracked that are part of a computed mapping
* If there is a missing model (a model alias is referenced but no model instance is bound to that alias), then it will return undefined.
* @param {string} computedAlias the name/alias of the computed mapping
* @returns {Object} a map from model name/alias to model instance. If there is a missing model (an model alias is referenced but no model
* instance is bound to that alias), then it will return undefined.
* @private
*/
__getComputedModels: function(computedAlias) {
var hasAllModels = !_.isUndefined(this.getMapping(computedAlias)),
models = {};
_.each(this.__getModelAliases(computedAlias), function(modelAlias) {
var model = this.getTrackedModel(modelAlias);
if (model) {
models[modelAlias] = model;
} else {
hasAllModels = false;
}
}, this);
return hasAllModels ? models : undefined;
},
/**
* Returns the aliases/names of models referenced in the computed mapping with the given alias
* @param {(string|Object)} computedAliasOrConfig the name/alias of the computed mapping or the computed mapping itself as
* an object if it hasn't been added as a mapping yet.
* @returns {string[]} an array of the model names/aliases referenced inside the computed mapping
* @private
*/
__getModelAliases: function(computedAliasOrConfig) {
var config,
modelAliases = [];
if (_.isString(computedAliasOrConfig)) {
config = this.getMapping(computedAliasOrConfig);
} else {
config = computedAliasOrConfig;
}
return _.filter(_.keys(config.mapping), function(key) {
return key != 'pull' && key != 'push';
});
},
/**
* Repackages a computed mapping to be easier consumed by methods wanting the model mappings tied to the model instances.
* Returns a list of objects that contain the model instance and the mapping for that model.
*
* @private
* @param {string} computedAlias the name/alias used for this computed
* @returns {object[]} a list of objects that contain the model instance under "model" and the mapping for that model under "fields".
*/
__getComputedModelConfigs: function(computedAlias) {
var hasAllModels = true,
config = this.getMapping(computedAlias),
modelConfigs = [];
_.each(this.__getModelAliases(computedAlias), function(modelAlias) {
var modelConfig = this.__createModelConfig(modelAlias, config.mapping[modelAlias]);
if (modelConfig) {
modelConfigs.push(modelConfig);
} else {
hasAllModels = false;
}
}, this);
return hasAllModels ? modelConfigs : undefined;
},
/**
* Pushes the form model values to the object models it is tracking and invokes save on each one. Returns a promise.
* @param {Object} [options]
* @param {boolean} [options.rollback=true] if true, when any object model fails to save, it will revert the object
* model attributes to the state they were before calling save. NOTE: if there are updates that happen
* to object models within the timing of this save method, the updates could be lost.
* @param {boolean} [options.force=true] if false, the form model will check to see if an update has been made
* to any object models it is tracking since it's last pull. If any stale data is found, save with throw an exception
* with attributes: {name: 'Stale data', staleModels: [Array of model cid's]}
* @returns a promise that will either resolve when all the models have successfully saved in which case the context returned
* is an array of the responses (order determined by first the array of models and then the array of models used by
* the computed values, normalized), or if any of the saves fail, the promise will be rejected with an array of responses.
* Note: the size of the failure array will always be one - the first model that failed. This is a side-effect of $.when
* @private
*/
__saveToModels: function(deferred, options) {
var staleModels,
formModel = this,
responsesSucceeded = 0,
responsesFailed = 0,
responses = {},
oldValues = {},
models = formModel.getTrackedModels(),
numberOfSaves = models.length;
// If we're not forcing a save, then throw an error if the models are stale
if (!options.force) {
staleModels = formModel.checkIfModelsAreStale();
if (staleModels.length > 0) {
throw {
name: 'Stale data',
staleModels: staleModels
};
}
}
// Callback for each response
function responseCallback(response, model, success) {
// Add response to a hash that will eventually be returned through the promise
responses[model.cid] = {
success: success,
response: response
};
// If we have reached the total of number of expected responses, then resolve or reject the promise
if (responsesFailed + responsesSucceeded === numberOfSaves) {
if (responsesFailed > 0) {
// Rollback if any responses have failed
if (options.rollback) {
_.each(formModel.getTrackedModels(), function(model) {
model.set(oldValues[model.cid]);
if (responses[model.cid].success) {
model.save();
}
});
}
formModel.trigger('save-fail', responses);
deferred.reject(responses);
} else {
formModel.trigger('save-success', responses);
deferred.resolve(responses);
}
}
}
// Grab the current values of the object models
_.each(models, function(model) {
oldValues[model.cid] = formModel.__getTrackedModelFields(model);
});
// Push the form model values to the object models
formModel.push();
// Call save on each object model
_.each(models, function(model) {
model.save().fail(function() {
responsesFailed++;
responseCallback(arguments, model, false);
}).done(function() {
responsesSucceeded++;
responseCallback(arguments, model, true);
});
});
},
/**
* Pulls in new information from tracked models using the mapping defined by the given alias.
* This works for both model mappings and computed value mappings
* @param {string} alias the name of the mapping that will be used during the pull
* @private
*/
__pull: function(alias) {
var config = this.getMapping(alias);
if (config.computed && config.mapping.pull) {
this.__invokeComputedPull.call({formModel: this, alias: alias});
} else if (config.computed) {
var modelAliases = this.__getModelAliases(alias);
_.each(modelAliases, function(modelAlias) {
var model = this.getTrackedModel(modelAlias);
if (model) {
this.__copyFields(config.mapping[modelAlias], this, model);
}
}, this);
} else {
var model = this.getTrackedModel(alias);
if (model) {
this.__copyFields(config.mapping, this, model);
}
}
},
/**
* Pushes form model information to tracked models using the mapping defined by the given alias.
* This works for both model mappings and computed value mappings
* @param {string} alias the name of the mapping that will be used during the push
* @private
*/
__push: function(alias) {
var config = this.getMapping(alias);
if (config.computed && config.mapping.push) {
var models = this.__getComputedModels(alias);
if (models) {
config.mapping.push.call(this, models);
}
} else if (config.computed) {
var modelAliases = this.__getModelAliases(alias);
_.each(modelAliases, function(modelAlias) {
var model = this.getTrackedModel(modelAlias);
if (model) {
this.__copyFields(config.mapping[modelAlias], model, this);
}
}, this);
} else {
var model = this.getTrackedModel(alias);
if (model) {
this.__copyFields(config.mapping, model, this);
}
}
},
/**
* Updates a single attribute in this form model.
* NOTE: requires the context of this function to be:
* {
* formModel: <this form model>,
* field: <the field being updated>
* }
* NOT the form model itself like if you called this.__updateFormField.
* @private
*/
__updateFormField: function(model, value) {
this.formModel.set(this.field, value);
this.formModel.__updateCache(model);
},
/**
* NOTE: When looking to update the form model manually, call this.pull().
* Updates this form model with the changed attributes of a given object model
* @param {external:Backbone-Model} model the object model that has been changed
* @private
*/
__updateFormModel: function(model) {
_.each(model.changedAttributes(), function(value, fieldName) {
this.set(fieldName, this.__cloneVal(value));
}, this);
this.__updateCache(model);
},
/**
* Updates the form model's snapshot of the model's attributes to use later
* @param {external:Backbone-Model} model the object model
* @param {Object} [cache=this.__cache] if passed an object (can be empty), this method will fill
* this cache object instead of this form model's __cache field
* @private
*/
__updateCache: function(model) {
if (!model) {
this.__cache = {};
_.each(this.getTrackedModels(), function(model) {
if (model) {
this.__updateCache(model);
}
}, this);
} else {
this.__cache[model.cid] = this.__generateHashValue(model);
}
},
/**
* Create a hash value of a simple object
* @param {Object} obj simple object with no functions
* @returns a hash value of the object
* @private
*/
__hashValue: function(obj) {
return JSON.stringify(obj);
},
/**
* Returns the alias/name bound to the model passed in. If a string is passed in, it will just return this string.
* @param {string|external:Backbone-Model} aliasOrModel If string, just returns this string. If a model instance, then the alias
* that is bound to the tracked model passed in will be found and returned.
* @returns {string} the alias
* @private
*/
__findAlias: function(aliasOrModel) {
var alias, objectModel;
if (_.isString(aliasOrModel)) {
alias = aliasOrModel;
} else {
objectModel = aliasOrModel;
alias = _.find(this.__currentObjectModels, function(model) {
return model == objectModel;
});
}
return alias;
},
/**
* @param {external:Backbone-Model} model the model to create the hash value from
* @returns {string} the hash value of the model making sure to only use the tracked fields
* @private
*/
__generateHashValue: function(model) {
var modelFields = this.__getTrackedModelFields(model);
return this.__hashValue(modelFields);
},
/**
* @returns {Object} a map of model's cid to the hash value of the model making sure to only use the tracked fields
* @private
*/
__generateAllHashValues: function() {
var currentHashValues = {};
_.each(this.getTrackedModels(), function(model) {
currentHashValues[model.cid] = this.__generateHashValue(model);
}, this);
return currentHashValues;
},
/**
* Deep clones the attributes. There should be no functions in the attributes
* @param {(Object|Array|string|number|boolean)} val a non-function value
* @returns the clone
* @private
*/
__cloneVal: function(val) {
var seed;
if (_.isArray(val)) {
seed = [];
} else if (_.isObject(val)) {
seed = {};
} else {
return val;
}
return $.extend(true, seed, val);
},
/**
* Attaches listeners to the tracked object models with callbacks that will copy new properties into this form model.
* @private
*/
__setupListeners: function() {
var model, modelConfigs,
formModel = this;
_.each(formModel.getMappings(), function(config, alias) {
if (config.computed) {
modelConfigs = formModel.__getComputedModelConfigs(alias);
_.each(modelConfigs, function(modelConfig) {
var model = modelConfig.model;
if (modelConfig.fields) {
_.each(modelConfig.fields, function(field) {
formModel.__listenToComputedValuesDependency(model, field, alias);
});
} else {
formModel.__listenToComputedValuesDependency(model, '', alias);
}
});
} else {
model = formModel.getTrackedModel(alias);
if (model) {
if (config.mapping) {
_.each(config.mapping, function(field) {
formModel.__listenToModelField(model, field);
});
} else {
formModel.__listenToModelField(model);
}
}
}
});
},
/**
* Copies fields from one backbone model to another. Is useful during a pull or push to/from Object models. The values will
* be deep cloned from the origin to the destination.
* @param {Array} [fields] a string of attribute names on the origin model that will be copied. Leave null if all attributes
* are to be copied
* @param {Backbone.Model} destination the backbone model that will have values copied into
* @param {Backbone.Model} origin the backbone model that will be used to grab values.
* @private
*/
__copyFields: function(fields, destination, origin) {
if ((!fields || fields === true) && this === origin && _.size(this.getTrackedModels()) > 1) {
// only copy attributes that exist on object model when the form model is tracking all the properties
// of that object model, but is also tracking other models as well.
fields = _.keys(destination.attributes);
}
if (fields) {
_.each(fields, function(field) {
destination.set(field, this.__cloneVal(origin.get(field)));
}, this);
} else {
destination.set(this.__cloneVal(origin.attributes));
}
},
/**
* Sets the mapping using the form model's default mapping or the options.mappings if available.
* Also sets the tracked models if the form model's default models or the options.models is provided.
* @param {Object} [options] See initialize options: 'mapping' and 'models'.
* @private
*/
__initMappings: function(options) {
var mapping,
models,
defaultMapping = _.result(this, 'mapping'),
defaultModels = _.result(this, 'models');
mapping = options.mapping || defaultMapping;
models = options.models || defaultModels;
if (mapping) {
this.setMappings(mapping, models);
}
},
/**
* Returns a map where the keys are the fields that are being tracked on tracked model and values are
* the with current values of those fields.
* @param {external:Backbone-Model} model the object model
* @returns {Object} aa map where the keys are the fields that are being tracked on tracked model and
* values are the with current values of those fields.
* @private
*/
__getTrackedModelFields: function(model) {
var allFields,
fieldsUsed = {},
modelFields = {},
modelConfigs = [];
_.each(this.__getAllModelConfigs(), function(modelConfig) {
if (modelConfig.model && modelConfig.model.cid === model.cid) {
modelConfigs.push(modelConfig);
}
});
allFields = _.reduce(modelConfigs, function(result, modelConfig) {
return result || !modelConfig.fields;