-
Notifications
You must be signed in to change notification settings - Fork 20
/
torso-bundle.js
7679 lines (7102 loc) · 301 KB
/
torso-bundle.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
/**
* The backbone Events reference
* @external Backbone-Events
* @see {@link http://backbonejs.org/#Events|Backbone.Events}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.Events = factory(root._, root.Backbone);
}
}(this, function(_, Backbone) {
'use strict';
/**
* Generic Events.
*
* @class Events
* @extends {external:Backbone-Events}
*
* @author [email protected], [email protected]
*
* @see <a href="../annotated/modules/Events.html">Events Annotated Source</a>
*/
var Events = _.extend({}, Backbone.Events);
return Events;
}));
/**
* The backbone Router reference
* @external Backbone-Router
* @extends external:Backbone-Events
* @see {@link http://backbonejs.org/#Router|Backbone.Router}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.Router = factory(root.Backbone);
}
}(this, function(Backbone) {
'use strict';
/**
* Backbone's router.
*
* @class Router
* @extends external:Backbone-Router
*
* @author [email protected]
*
* @see <a href="../annotated/modules/Router.html">Router Annotated Source</a>
*/
return Backbone.Router.extend(/** @lends Router# */{});
}));
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('backbone'), require('jquery'));
} else {
factory(root.Backbone, root.$);
}
}(this, function(Backbone, $) {
'use strict';
Backbone.$ = $;
return true;
}));
/**
* The handlebars reference
* @external Handlebars
* @see {@link https://handlebarsjs.com/|Handlebars}
*/
/**
* The handlebars Template reference
* @external Handlebars-Template
* @see {@link https://handlebarsjs.com/|Handlebars}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'));
} else {
root.Torso = root.Torso || {};
root.Torso.Utils = root.Torso.Utils || {};
root.Torso.Utils.handlebarsUtils = factory(root._);
}
}(this, function(_) {
'use strict';
/**
* Extensions to handlebars helpers.
*
* Adds additonal helpers to {@link external:Handlebars}
*
* @function handlebarsUtils
* @param {external:Handlebars} Handlebars Add the helpers to this Handlebars object.
*
* @author [email protected], [email protected]
*
* @see {@link HandlebarsHelper} for the added helpers.
* @see <a href="../annotated/modules/handlebarsUtils.html">handlebarsUtils Annotated Source</a>
*/
/** @namespace HandlebarsHelper */
return function(Handlebars) {
var FEEDBACK_KEY = 'feedback';
var MODEL_KEY = 'model';
/**
* Usage: {{labelFor 'fieldName' value="suffix"}}
*
* Generates: for="field-name-suffix"
*
* Usage: {{labelFor 'fieldName[x].sub' value="demo" x=123}}
*
* Generates: for="field-name-123_sub-demo"
*
* Usage: {{labelFor 'fieldName[bar].sub' value="demo" bar="abc"}}
*
* Generates: for="field-name_abc_sub-demo"
*
* @method HandlebarsHelper.labelFor
* @param {string} field The field name to convert to a compliant "for" attribute
* @param {Object} options The handlebars context. Always passed in as the final argument.
* @param {string} [option.hash.value] The value tacked on to the end of the field string (useful for radio and checkbox)
* @returns {string} Compliant HTML generating the "for" attribute
*/
Handlebars.registerHelper('labelFor', function(field, options) {
options = _.extend(options, {noValueAttr: true});
return Handlebars.helpers.formAttr(field, 'for', options);
});
/**
* Usage: {{bindModel 'fieldName' value='suffix'}}
*
* Generates: id="field-name-suffix" name="field-name" data-model="fieldName" data-feedback="fieldName" value="demo"
*
* Usage: {{bindModel 'fieldName[x].sub' value='demo' x=123}}
*
* Generates: data-model="fieldName[123].sub" data-feedback="fieldName[123].sub" name="field-name-123_sub"
* id="field-name-123_sub-demo" value="demo"
*
* Usage: {{bindModel 'fieldName[bar].sub' value='demo' bar='abc'}}
*
* Generates: data-model="fieldName.abc.sub" data-feedback="fieldName[abc].sub" name="field-name_abc_sub"
id="field-name_abc_sub-demo" value="demo"
*
* @method HandlebarsHelper.bindModel
* @param {string} field The field name to convert to compliant id, name, data-model, and data-feedback attributes
* @param {Object} options The handlebars context. Always passed in as the final argument.
* @param {string} [options.hash.value] The value tacked on to the end of the field string (useful for radio and checkbox)
* @returns {string} Compliant HTML generating the id, name, data-model, and data-feedback attributes
*/
Handlebars.registerHelper('bindModel', function(field, options) {
return Handlebars.helpers.formAttr(field, MODEL_KEY + ', ' + FEEDBACK_KEY + ', name, id', options);
});
/**
* Usage: {{feedback 'fieldName'}}
*
* Generates: data-feedback="fieldName"
*
* Usage: {{feedback 'fieldName[x].sub' value='demo' x=123}}
*
* Generates: data-feedback="fieldName[123].sub"
*
* Usage: {{feedback 'fieldName[bar].sub value='demo' bar='abc'}}
*
* Generates: data-feedback="fieldName[abc].sub"
*
* @method HandlebarsHelper.feedback
* @param {string} field The field name to convert to a compliant data-feedback attribute
* @param {Object} options The handlebars context. Always passed in as the final argument.
* @returns {string} Compliant HTML generating the data-feedback attribute
*/
Handlebars.registerHelper('feedback', function(field, options) {
options = _.extend(options, {noValueAttr: true});
return Handlebars.helpers.formAttr(field, FEEDBACK_KEY, options);
});
/**
* Usage: {{formAttr 'fieldName[x].sub' 'id, for' value='demo' x=123}}
*
* Generates: id="field-name-123_sub-demo" for="field-name-123_sub-demo" value="demo"
*
* Usage: {{feedback 'fieldName[bar].sub value='demo' bar='abc'}}
*
* Generates: id="field-name_abc_sub-demo" for="field-name_abc_sub-demo" value="demo"
*
* @method HandlebarsHelper.formAttr
* @param {string} field The field name to convert to a compliant data-feedback attribute
* @param {Object} options The handlebars context. Always passed in as the final argument.
* @param {string} [options.hash.value] The value tacked on to the end of the field string (useful for radio and checkbox)
* @param {boolean} [options.noValueAttr] when options.noValueAttr is set to true,
then it will not generate the "value" attribute in the DOM.
* @returns {string} Compliant HTML generating the data-feedback attribute
*/
Handlebars.registerHelper('formAttr', function(field, attrs, options) {
var i, attrName,
value = (options.hash ? options.hash.value : undefined),
res = Handlebars.helpers.injectFieldIndices(field, options.hash),
resWithArrayNotation = Handlebars.helpers.injectFieldIndices(field, options.hash, { forceArrayNotation: true }),
attributes = '';
attrs = attrs.split(',');
for (i = 0; i < attrs.length; i++) {
attrName = attrs[i].trim();
var attrEnd = (i === attrs.length - 1) ? '"' : '" ';
if (attrName === FEEDBACK_KEY) {
// Feedback needs to always use array notation because of the way it finds the element (by stripping [] contents).
attributes += 'data-feedback="' + resWithArrayNotation + attrEnd;
} else if (attrName === MODEL_KEY) {
attributes += 'data-model="' + res + attrEnd;
} else if (attrName === 'name') {
attributes += 'name="' + Handlebars.helpers.dasherize(res) + attrEnd;
} else if (attrName === 'id') {
attributes += 'id="' + Handlebars.helpers.dasherize(res);
if (value !== undefined) {
attributes += '-' + value;
}
attributes += attrEnd;
} else if (attrName === 'for') {
attributes += 'for="' + Handlebars.helpers.dasherize(res);
if (value !== undefined) {
attributes += '-' + value;
}
attributes += attrEnd;
}
}
if (value !== undefined && !options.noValueAttr) {
attributes += ' value="' + value + '"';
}
return new Handlebars.SafeString(attributes);
});
/**
* Usage: {{feedback 'fieldName[x].sub'}}
*
* Generates: field-name[x]_sub
*
* @method HandlebarsHelper.dasherize
* @param {string} str The input string to make HTML compliant (convert to dashes)
* @returns {string} HTML complicant / dasherized string
*/
Handlebars.registerHelper('dasherize', function(str) {
var camelCaseRemoved, dotsRemoved, bracesRemoved;
camelCaseRemoved = str.replace(/([A-Z])/g, function(rep) {
return '-' + rep.toLowerCase();
});
dotsRemoved = camelCaseRemoved.replace(/\./g, function() {
return '_';
});
bracesRemoved = dotsRemoved.replace(/\[[0-9]+\]/g, function(rep) {
return '-' + rep.substring(1, rep.length - 1);
});
return bracesRemoved;
});
/**
* Usage: injectFieldIndices('test[x]-thisIsRegular-y', {x: 123, y: 456} and 'foo[x].abc', x='bar');
*
* Generates: 'test[123]-thisIsRegular-y' and 'foo.bar.abc'
*
* if options.forceArrayNotation is set then:
*
* Generates: 'test[123]-thisIsRegular-y' and 'foo[bar].abc'
*
* @method HandlebarsHelper.injectFieldIndices
* @param {string} field The field name
* @param {Object} indexMap A map of variables
* @param {Object} options named parameters
* @param {boolean} [options.forceArrayNotation=false] Force the usage of [] insetad of . for string values.
* @returns {string} the field string with array variables substituted
*/
Handlebars.registerHelper('injectFieldIndices', function(field, indexMap, options) {
if (indexMap) {
return field.replace(/\[.+?\]/g, function(m) {
var newIndex = indexMap[m.substring(1, m.length - 1)];
var indexToken = '[' + (newIndex === undefined ? '' : newIndex) + ']';
var forceArrayNotation = options && options.forceArrayNotation;
if (_.isString(newIndex) && isNaN(newIndex) && !forceArrayNotation) {
indexToken = '.' + newIndex;
}
return indexToken;
});
} else {
return field;
}
});
};
}));
/**
* The backbone History reference
* @external Backbone-History
* @extends external:Backbone-Events
* @see {@link http://backbonejs.org/#History|Backbone.History}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.history = factory(root.Backbone);
}
}(this, function(Backbone) {
'use strict';
/**
* Backbone's history object.
*
* @class history
* @extends external:Backbone-History
*
* @author [email protected]
*
* @see <a href="../annotated/modules/history.html">history Annotated Source</a>
*/
return Backbone.history;
}));
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.registry = factory(root._, root.Backbone);
}
}(this, function(_, Backbone) {
'use strict';
/**
* Registry of instantiated Torso objects
*
* @class registry
* @extends external:Backbone-Events
*
* @author [email protected]
*
* @see <a href="../annotated/modules/registry.html">registry Annotated Source</a>
*/
var Registry = function() {
/**
* The registered cells keyed by their unique cid.
* @name cells
* @instance
* @type {Object.<string, Cell>}
* @memberof registry
*/
this.cells = {};
/**
* The registered models keyed by their unique cid.
* @name models
* @instance
* @type {Object.<string, Model>}
* @memberof registry
*/
this.models = {};
/**
* The registered services keyed by their unique cid.
* @name services
* @instance
* @type {Object.<string, ServiceCell>}
* @memberof registry
*/
this.services = {};
/**
* The registered views keyed by their unique cid.
* @name views
* @instance
* @type {Object.<string, View>}
* @memberof registry
*/
this.views = {};
};
_.extend(Registry.prototype, Backbone.Events, /** @lends registry# */{
/**
* The prefix to use for this object's cid.
* @type {string}
*/
cidPrefix: 'r',
/**
* Add the model to the model cache when it is initialized.
* @param {Torso.Model} model the model to add to the models cache.
*/
modelInitialized: function(model) {
this.__initialize(model, this.models);
},
/**
* Add the cell to the cell cache when it is initialized.
* @param {Torso.Cell} cell the cell to add to the cells cache.
*/
cellInitialized: function(cell) {
this.__initialize(cell, this.cells);
},
/**
* Add the view to the view cache when it is initialized.
* @param {Torso.View} view the view to add to the views cache.
*/
viewInitialized: function(view) {
this.__initialize(view, this.views);
},
/**
* Add the service to the model service when it is initialized.
* @param {Torso.ServiceCell} service the service to add to the services cache.
*/
serviceInitialized: function(service) {
this.__initialize(service, this.services);
},
/**
* Initialize the given object in the given cache.
* @param {Backbone.Events} obj any object that implements/extends backbone events.
* @param {string} obj.cid the unique identifier for the object.
* @param {Object} cache the cache to add the object to.
* @private
*/
__initialize: function(obj, cache) {
cache[obj.cid] = obj;
this.listenToOnce(obj, 'before-dispose', function() {
delete cache[obj.cid];
});
},
/**
* Dispose of all items in all of the caches (Models, Cells, Services and Views).
*/
disposeAll: function() {
this.disposeAllModels();
this.disposeAllCells();
this.disposeAllServices();
this.disposeAllViews();
},
/**
* Dispose of all items in the Models cache.
*/
disposeAllModels: function() {
this.__disposeCache(this.models);
},
/**
* Dispose of all items in the Cells cache.
*/
disposeAllCells: function() {
this.__disposeCache(this.cells);
},
/**
* Dispose of all items in the Services cache.
*/
disposeAllServices: function() {
this.__disposeCache(this.services);
},
/**
* Dispose of all items in the Views cache.
*/
disposeAllViews: function() {
this.__disposeCache(this.views);
},
/**
* Invoke dispose on all the items in the given cache.
* @param {Object} cache to invoke dispose on each member.
* @private
*/
__disposeCache: function(cache) {
var objects = _.values(cache);
_.invoke(objects, 'dispose');
}
});
var registry = new Registry();
return registry;
}));
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'backbone.stickit'], factory);
} else if (typeof exports === 'object') {
require('backbone.stickit');
factory(require('backbone'));
} else {
factory(root.Backbone);
}
}(this, function(Backbone) {
'use strict';
/**
* Extensions to stickit handlers.
*
* @function stickitUtils
*
* @author [email protected], [email protected]
*
* @see <a href="../annotated/modules/stickitUtils.html">stickitUtils Annotated Source</a>
*/
Backbone.Stickit.addHandler({
selector: 'input[type="radio"]',
events: ['change'],
update: function($el, val) {
$el.prop('checked', false);
$el.filter('[value="' + val + '"]').prop('checked', true);
},
getVal: function($el) {
return $el.filter(':checked').val();
}
});
}));
/**
* The jQuery reference
* @external jQuery
* @property {external:jQuery-Deferred} Deferred
* @see {@link https://api.jquery.com/category/selectors/|jQuery}
*/
/**
* The jQuery Deferred reference
* @external jQuery-Deferred
* @see {@link https://api.jquery.com/category/deferred-object/|jQuery.Deferred}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.Utils = root.Torso.Utils || {};
root.Torso.Utils.templateRenderer = factory(root._, root.Backbone);
}
}(this, function(_, Backbone) {
'use strict';
var $ = Backbone.$;
/**
* Changes DOM Nodes that are different, and leaves others untouched.
*
* Algorithm:
* Delegates to a particular swapMethod, depending on the Node type.
* Recurses for nested Element Nodes only.
* There is always room for optimizing this method.
*
* @memberof templateRenderer
* @param {Node} currentNode The DOM Node corresponding to the existing page content to update
* @param {Node} newNode The detached DOM Node representing the desired DOM subtree
* @param {Array} ignoreElements Array of jQuery selectors for DOM Elements to ignore during render. Can be an expensive check.
*/
function hotswap(currentNode, newNode, ignoreElements) {
var newNodeType = newNode.nodeType,
currentNodeType = currentNode.nodeType,
swapMethod;
if(newNodeType !== currentNodeType) {
$(currentNode).replaceWith(newNode);
} else {
swapMethod = swapMethods[newNodeType] || swapMethods['default'];
swapMethod(currentNode, newNode, ignoreElements);
}
}
/**
* Stickit will rely on the 'stickit-bind-val' jQuery data attribute to determine the value to use for a given option.
* If the value DOM attribute is not the same as the stickit-bind-val, then this will clear the jquery data attribute
* so that stickit will use the value DOM attribute of the option. This happens when templateRenderer merges
* the attributes of the newNode into a current node of the same type when the current node has the stickit-bind-val
* jQuery data attribute set.
*
* If the node value is not set, then the stickit-bind-val might be how the view is communicating the value for stickit to use
* (possibly in the case of non-string values). In this case trust the stickit-bind-val.
*
* @param {Node} node the DoM element to test and fix the stickit data on.
*/
function cleanupStickitData(node) {
var $node = $(node);
var stickitValue = $node.data('stickit-bind-val');
if (node.tagName === 'OPTION' && node.value !== undefined && stickitValue !== node.value) {
$node.removeData('stickit-bind-val');
}
}
/*
* Swap method for Element Nodes
* @param {Element} currentNode The pre-existing DOM Element to update
* @param {Element} newNode The detached DOM Element representing the desired DOM Element subtree
* @param {Array} ignoreElements Array of jQuery selectors for DOM Elements to ignore during render. Can be an expensive check.
*/
function swapElementNodes(currentNode, newNode, ignoreElements) {
var currentAttr, shouldIgnore, $currChildNodes, $newChildNodes, currentAttributes,
$currentNode = $(currentNode),
$newNode = $(newNode),
idx = 0;
shouldIgnore = _.some(ignoreElements, function(selector) {
return $currentNode.is(selector);
});
if (shouldIgnore) {
return;
}
// Handle tagname changes with full replacement
if (newNode.tagName !== currentNode.tagName) {
$currentNode.replaceWith(newNode);
return;
}
// Remove current attributes that have changed
// This is necessary, because some types of attributes cannot be removed
// without causing a browser error.
currentAttributes = currentNode.attributes;
var prevLength = currentAttributes.length;
while (idx < currentAttributes.length) {
currentAttr = currentAttributes[idx].name;
if (newNode.getAttribute(currentAttr)) {
idx++;
} else {
currentNode.removeAttribute(currentAttr);
if (prevLength === currentAttributes.length) {
// bail since we can't remove the attribute.
$currentNode.replaceWith(newNode);
return;
}
prevLength = currentAttributes.length;
}
}
// Set new attributes
_.each(newNode.attributes, function(attrib) {
currentNode.setAttribute(attrib.name, attrib.value);
});
cleanupStickitData(currentNode);
// Quick check to see if we need to bother comparing sub-levels
if ($currentNode.html() === $newNode.html()) {
return;
}
// Include all child nodes, including text and comment nodes
$newChildNodes = $newNode.contents();
$currChildNodes = $currentNode.contents();
// If the DOM lists are different sizes, perform a hard refresh
if ($newChildNodes.length !== $currChildNodes.length) {
$currentNode.html($newNode.html());
return;
}
// Perform a recursive hotswap for all children nodes
$currChildNodes.each(function(index, currChildNode) {
hotswap(currChildNode, $newChildNodes.get(index), ignoreElements);
});
}
/*
* Swap method for Text, Comment, and CDATA Section Nodes
* @param {Node} currentNode The pre-existing DOM Node to update
* @param {Node} newNode The detached DOM Node representing the desired DOM Node subtree
*/
function updateIfNodeValueChanged(currentNode, newNode){
var nodeValueChanged = newNode.nodeValue !== currentNode.nodeValue;
if (nodeValueChanged) {
$(currentNode).replaceWith(newNode);
}
}
/*
* Map of nodeType to hot swap implementations.
* NodeTypes are hard-coded integers per the DOM Level 2 specification instead of
* references to constants defined on the window.Node object for IE8 compatibility
*/
var swapMethods = {
1: swapElementNodes, // ELEMENT_NODE
3: updateIfNodeValueChanged, // TEXT_NODE
4: updateIfNodeValueChanged, // CDATA_SECTION_NODE
8: updateIfNodeValueChanged, // COMMENT_NODE
default: function(currentNode, newNode) {
$(currentNode).replaceWith(newNode);
}
};
/**
* Static Template Engine.
* All template renders should be piped through this method.
*
* @namespace templateRenderer
*
* @author [email protected]
*
* @see <a href="../annotated/modules/templateRenderer.html">templateRenderer Annotated Source</a>
*/
var templateRenderer = /** @lends templateRenderer */ {
/**
* Performs efficient re-rendering of a template.
* @param {external:jQuery} $el The Element to render into
* @param {external:Handlebars-Template} template The HBS template to apply
* @param {Object} context The context object to pass to the template
* @param {Object} [opts] Other options
* @param {boolean} [opts.force=false] Will forcefully do a fresh render and not a diff-render
* @param {string} [opts.newHTML] If you pass in newHTML, it will not use the template or context, but use this instead.
* @param {Array} [opts.ignoreElements] jQuery selectors of DOM elements to ignore during render. Can be an expensive check
*/
render: function($el, template, context, opts) {
var newDOM, newHTML,
el = $el.get(0);
opts = opts || {};
newHTML = opts.newHTML || template(context);
if (opts.force) {
$el.html(newHTML);
} else {
newDOM = this.copyTopElement(el);
$(newDOM).html(newHTML);
this.hotswapKeepCaret(el, newDOM, opts.ignoreElements);
}
},
/**
* Call this.hotswap but also keeps the caret position the same
* @param {Node} currentNode The DOM Node corresponding to the existing page content to update
* @param {Node} newNode The detached DOM Node representing the desired DOM subtree
* @param {Array} ignoreElements Array of jQuery selectors for DOM Elements to ignore during render. Can be an expensive check.
*/
hotswapKeepCaret: function(currentNode, newNode, ignoreElements) {
var currentCaret, activeElement,
currentNodeContainsActiveElement = false;
try {
activeElement = document.activeElement;
} catch (error) {
activeElement = null;
}
if (activeElement && currentNode && $.contains(activeElement, currentNode)) {
currentNodeContainsActiveElement = true;
}
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
currentCaret = this.getCaretPosition(activeElement);
}
this.hotswap(currentNode, newNode, ignoreElements);
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
this.setCaretPosition(activeElement, currentCaret);
}
},
// See above function declaration for method-level documentation
hotswap: hotswap,
/**
* Produces a copy of the element tag with attributes but with no contents
* @param {Element} el the DOM element to be copied
* @returns {Element} a shallow copy of the element with no children but with attributes
*/
copyTopElement: function(el) {
var newDOM = document.createElement(el.tagName);
_.each(el.attributes, function(attrib) {
newDOM.setAttribute(attrib.name, attrib.value);
});
return newDOM;
},
/**
* Determines if the element supports selection. As per spec, https://html.spec.whatwg.org/multipage/forms.html#do-not-apply
* selection is only allowed for text, search, tel, url, password. Other input types will throw an exception in chrome
* @param {Element} el the DOM element to check
* @returns {boolean} boolean indicating whether or not the selection is allowed for {Element} el
*/
supportsSelection : function (el) {
return (/text|password|search|tel|url/).test(el.type);
},
/**
* Method that returns the current caret (cursor) position of a given element.
* Source: http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field
* @param {element} elem the DOM element to check caret position
* @returns {Integer} the cursor index of the given element.
*/
getCaretPosition: function(elem) {
// range {IE selection object}
// iCaretPos {Integer} will store the final caret position
var range,
iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
elem.focus();
// To get cursor position, get empty selection range
range = document.selection.createRange();
// Move selection start to 0 position
range.moveStart('character', -elem.value.length);
// The caret position is selection length
iCaretPos = range.text.length;
} else if (elem.selectionStart || elem.selectionStart === 0) {
// Firefox support
iCaretPos = elem.selectionStart;
}
// Return results
return iCaretPos;
},
/**
* Method that returns sets the current caret (cursor) position of a given element and puts it in focus.
* Source: http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox
* @param {element} elem
* @param {Integer} caretPos The caret index to set
* @returns {Integer} the cursor index of the given element.
*/
setCaretPosition: function(elem, caretPos) {
var range;
if (elem) {
if (elem.createTextRange) {
// IE support
range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else if (elem.selectionStart || elem.selectionStart === 0) {
// Firefox support
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else {
// At least focus the element if nothing else
elem.focus();
}
}
}
};
return templateRenderer;
}));
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
root.Torso = root.Torso || {};
root.Torso.Mixins = root.Torso.Mixins || {};
root.Torso.Mixins.cache = factory(root._, root.Backbone);
}
}(this, function(_, Backbone) {
var $ = Backbone.$;
/**
* Custom additions to the Backbone Collection object.
* - safe disposal methods for memory + event management
* - special functional overrides to support ID registration for different views
*
* @mixin cacheMixin
*
* @author [email protected], [email protected]
*
* @see <a href="../annotated/modules/mixins/cacheMixin.html">cacheMixin Annotated Source</a>
*/
var mixin = function(base) {
var cacheMixin, createRequesterCollectionClass;
/**
* Returns a new class of collection that inherits from the parent but not the cacheMixin
* and adds a requesterMixin that connects this cache to it's parent
*
* @class PrivateCollection
* @extends Collection
* @param {external:Backbone-Collection} parent the parent of the private collection
* @param {string} guid the unique code of the owner of this private collection
*/
createRequesterCollectionClass = function(parent, guid) {
return parent.constructor.extend((function(parentClass, parentInstance, ownerKey) {
/**
* A mixin that overrides base collection methods meant for cache's and tailors them
* to a requester.
* @alias PrivateCollection.prototype
*/
var requesterMixin = {
/**
* @returns {Array} array of ids that this collection is tracking
*/
getTrackedIds: function() {
return this.trackedIds;
},
/**
* Will force the cache to fetch just the registered ids of this collection
* @param [options] - argument options
* @param {Array} [options.idsToFetch=collectionTrackedIds] - A list of request Ids, will default to current tracked ids
* @param {Object} [options.setOptions] - if a set is made, then the setOptions will be passed into the set method
* @returns {Promise} promise that will resolve when the fetch is complete
*/
fetch: function(options) {
options = options || {};
options.idsToFetch = options.idsToFetch || this.trackedIds;
options.setOptions = options.setOptions || {remove: false};
return this.__loadWrapper(function() {
if (options.idsToFetch && options.idsToFetch.length) {
return parentInstance.fetchByIds(options);
} else {
return $.Deferred().resolve().promise();
}
});
},
/**
* Will force the cache to fetch a subset of this collection's tracked ids
* @param {Array} ids array of model ids
* @param {Object} [options] if given, will pass the options argument to this.fetch. Note, will not affect options.idsToFetch
* @returns {Promise} promise that will resolve when the fetch is complete
*/
fetchByIds: function(ids, options) {
options = options || {};
options.idsToFetch = _.intersection(ids, this.getTrackedIds());
return this.fetch(options);
},
/**
* Pass a list of ids to begin tracking. This will reset any previous list of ids being tracked.
* Overrides the Id registration system to route via the parent collection
* @param ids The list of ids that this collection wants to track
*/
trackIds: function(ids) {
this.remove(_.difference(this.trackedIds, ids));
parentInstance.registerIds(ids, ownerKey);
this.trackedIds = ids;
},
/**
* Adds a new model to the requester collection and tracks the model.id
* @param {external:Backbone-Model} model the model to be added
*/
addModelAndTrack: function(model) {
this.add(model);
parentInstance.add(model);
this.trackNewId(model.id);
},
/**
* Tracks a new id
* @param {(string|Number)} id the id attribute of the model
*/
trackNewId: function(id) {
this.trackIds(this.getTrackedIds().concat(id));
},
/**
* Will begin tracking the new ids and then ask the cache to fetch them
* This will reset any previous list of ids being tracked.
* @returns the promise of the fetch by ids
*/
trackAndFetch: function(newIds) {
this.trackIds(newIds);
return this.fetch();
},
/**
* Will force the cache to fetch any of this collection's tracked models that are not in the cache
* while not fetching models that are already in the cache. Useful when you want the effeciency of
* pulling models from the cache and don't need all the models to be up-to-date.
*
* If the ids being fetched are already being fetched by the cache, then they will not be re-fetched.
*
* The resulting promise is resolved when ALL items in the process of being fetched have completed.
* The promise will resolve to a unified data property that is a combination of the completion of all of the fetches.
*
* @param {Object} [options] if given, will pass the options argument to this.fetch. Note, will not affect options.idsToFetch
* @returns {Promise} promise that will resolve when the fetch is complete with all of the data that was fetched from the server.
* Will only resolve once all ids have attempted to be fetched from the server.
*/
pull: function(options) {
options = options || {};
//find ids that we don't have in cache and aren't already in the process of being fetched.
var idsNotInCache = _.difference(this.getTrackedIds(), _.pluck(parentInstance.models, 'id'));
var idsWithPromises = _.pick(parentInstance.idPromises, idsNotInCache);
// Determine which ids are already being fetched and the associated promises for those ids.
options.idsToFetch = _.difference(idsNotInCache, _.uniq(_.flatten(_.keys(idsWithPromises))));
var thisFetchPromise = this.fetch(options);
// Return a promise that resolves when all ids are fetched (including pending ids).
var allPromisesToWaitFor = _.flatten(_.values(idsWithPromises));