-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathView.js
1524 lines (1427 loc) · 64.8 KB
/
View.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 View reference
* @external Backbone-View
* @extends external:Backbone-Events
* @see {@link http://backbonejs.org/#View|Backbone.View}
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone', './templateRenderer', './Cell', './NestedCell', './registry'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'), require('./templateRenderer'), require('./Cell'), require('./NestedCell'), require('./registry'));
} else {
root.Torso = root.Torso || {};
root.Torso.View = factory(root._, root.Backbone, root.Torso.Utils.templateRenderer, root.Torso.Cell, root.Torso.NestedCell, root.Torso.registry);
}
}(this, function(_, Backbone, templateRenderer, Cell, NestedCell, registry) {
'use strict';
var $ = Backbone.$;
/**
* ViewStateCell is a NestedCell that holds view state data and can trigger
* change events. These change events will propagate up and trigger on the view
* as well.
*
* @class ViewStateCell
* @extends {NestedCell}
*
* @param {Object} attrs the initial values to set on the cell - inherited from {@link NestedCell}.
* @param {Object} opts options for the cell.
* @param {external:Backbone-View} opts.view the view that these options are tied to.
*
* @see <a href="../annotated/modules/View.html">View Annotated Source</a>
*/
var ViewStateCell = NestedCell.extend(/** @lends ViewStateCell# */{
/**
* @constructs
* @param {Object} attrs the initial values to set on the cell - inherited from {@link NestedCell}.
* @param {Object} opts options for the cell.
* @param {external:Backbone-View} opts.view the view that these options are tied to.
*/
initialize: function(attrs, opts) {
opts = opts || {};
this.view = opts.view;
},
/**
* Retrigger view state change events on the view as well.
* @override
*/
trigger: function(name) {
if (name === 'change' || name.indexOf('change:') === 0) {
View.prototype.trigger.apply(this.view, arguments);
}
if (name.indexOf('change:hide:') === 0) {
this.view.render();
}
NestedCell.prototype.trigger.apply(this, arguments);
}
});
var View = Backbone.View.extend(/** @lends View# */{
/**
* Cell that can be used to save state for rendering the view.
* @type {ViewStateCell}
*/
viewState: null,
template: undefined,
feedback: null,
feedbackCell: null,
behaviors: null,
templateRendererOptions: undefined,
prepareFields: null,
injectionSites: null,
__behaviorInstances: null,
__childViews: null,
__sharedViews: null,
__isActive: false,
__isAttachedToParent: false,
__isDisposed: false,
__attachedCallbackInvoked: false,
__feedbackOnEvents: null,
__feedbackListenToEvents: null,
/**
* Array of feedback when-then-to's. Example:
* [{
* when: {'@fullName': ['change']},
* then: function(event) { return {text: this.feedbackCell.get('fullName')};},
* to: 'fullName-feedback'
* }]
* @private
* @property {Array} feedback
*/
/**
* Overrides constructor to create needed fields and invoke activate/render after initialization
*
* Generic View that deals with:
* - Creation of private collections
* - Lifecycle of a view
*
* @class View
* @extends {external:Backbone-View}
* @author ariel.wexler@vecna.com, kent.willis@vecna.com
* @constructs
*
* @see <a href="../annotated/modules/View.html">View Annotated Source</a>
*/
constructor: function(options) {
options = options || {};
this.viewState = new ViewStateCell({}, { view: this });
this.feedbackCell = new Cell();
this.__childViews = {};
this.__sharedViews = {};
this.__injectionSiteMap = {};
this.__feedbackOnEvents = [];
this.__feedbackListenToEvents = [];
this.template = options.template || this.template;
this.templateRendererOptions = options.templateRendererOptions || this.templateRendererOptions;
this.__initializeBehaviors(options);
this.trigger('initialize:begin');
Backbone.View.apply(this, arguments);
this.trigger('initialize:complete');
if (!options.noActivate) {
this.activate();
}
// Register by default.
var shouldRegister = _.isUndefined(options.register) || _.isNull(options.register) || options.register;
if (shouldRegister) {
registry.viewInitialized(this);
}
},
/**
* Alias to this.viewState.get()
*/
get: function() {
return this.viewState.get.apply(this.viewState, arguments);
},
/**
* Alias to this.viewState.set()
*/
set: function() {
return this.viewState.set.apply(this.viewState, arguments);
},
/**
* Alias to this.viewState.has()
*/
has: function() {
return this.viewState.has.apply(this.viewState, arguments);
},
/**
* Alias to this.viewState.unset()
*/
unset: function() {
return this.viewState.unset.apply(this.viewState, arguments);
},
/**
* Alias to this.viewState.toJSON()
*/
toJSON: function() {
return this.viewState.toJSON();
},
/**
* @param {string} alias the name/alias of the behavior
* @return {Torso.Behavior} the behavior instance if one exists with that alias
*/
getBehavior: function(alias) {
if (this.__behaviorInstances) {
return this.__behaviorInstances[alias];
}
},
/**
* prepareFields can be used to augment the default render method contents.
* See __getPrepareFieldsContext() for more details on how to configure them.
*
* @return {Object} context for a render method. Defaults to:
* {view: this.viewState.toJSON(), model: this.model.toJSON()}
*/
prepare: function() {
return this.__getPrepareFieldsContext();
},
/**
* Extension point to augment the template context with custom content.
* @function
* @param context the context you can modify
* @return {Object} [Optional] If you return an object, it will be merged with the context
*/
_prepare: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Rebuilds the html for this view's element. Should be able to be called at any time.
* Defaults to using this.templateRender. Assumes that this.template is a javascript
* function that accepted a single JSON context.
* The render method returns a promise that resolves when rendering is complete. Typically render
* is synchronous and the rendering is complete upon completion of the method. However, when utilizing
* transitions/animations, the render process can be asynchronous and the promise is useful to know when it has finished.
* @return {Promise} a promise that when resolved signifies that the rendering process is complete.
*/
render: function() {
if (this.isDisposed()) {
throw new Error('Render called on a view that has already been disposed.');
}
var view = this;
this.trigger('render:begin');
if (this.prerender() === false) {
this.trigger('render:aborted');
return $.Deferred().resolve().promise();
}
this.__updateInjectionSiteMap();
this.trigger('render:before-dom-update');
this.detachTrackedViews();
this.updateDOM();
if (this.__pendingAttachInfo) {
this.__performPendingAttach();
}
this.trigger('render:after-dom-update');
this.delegateEvents();
this.trigger('render:after-delegate-events');
this.unregisterTrackedViews({ shared: true });
this.trigger('render:before-attach-tracked-views');
this.__attachViewsFromInjectionSites();
var promises = this.attachTrackedViews();
return $.when.apply($, _.flatten([promises])).done(function() {
view.postrender();
view.trigger('render:complete');
view.__injectionSiteMap = {};
view.__lastTrackedViews = {};
});
},
/**
* Hook during render that is invoked before any DOM rendering is performed.
* This method can be overwritten as usual OR extended using <baseClass>.prototype.prerender.apply(this, arguments);
* NOTE: if you require the view to be detached from the DOM, consider using _detach callback
* @return {Promise|Array<Promise>} you can optionally return one or more promises that when all are resolved, prerender is finished. Note: render logic will not wait until promises are resolved.
*/
prerender: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Produces and sets this view's elements DOM. Used during the rendering process. Override if you have custom DOM update logic.
* Defaults to using the stanrdard: this.templateRender(this.$el, this.template, this.prepare(), templateRendererOptions);
* this.templateRendererOptions is an object or function defined on the view that is passed into the renderer.
* Examples include: views with no template or multiple templates, or if you wish to use a different rendering engine than the templateRenderer or wish to pass options to it.
*/
updateDOM: function() {
if (this.template) {
var templateRendererOptions = _.result(this, 'templateRendererOptions');
this.templateRender(this.$el, this.template, this.prepare(), templateRendererOptions);
}
},
/**
* Updates this view element's class attribute with the value provided.
* If no value provided, removes the class attribute of this view element.
* @param {string} newClassName the new value of the class attribute
*/
updateClassName: function(newClassName) {
if (newClassName === undefined) {
this.$el.removeAttr('class');
} else {
this.$el.attr('class', newClassName);
}
},
/**
* Hook during render that is invoked after all DOM rendering is done and tracked views attached.
* This method can be overwritten as usual OR extended using <baseClass>.prototype.postrender.apply(this, arguments);
* NOTE: if you require the view to be attached to the DOM, consider using _attach callback
* @return {Promise|Array<Promise>} you can optionally return one or more promises that when all are resolved, postrender is finished. Note: render logic will not wait until promises are resolved.
*/
postrender: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Hotswap rendering system reroute method.
* See Torso.templateRenderer#render for params
*/
templateRender: function(el, template, context, opts) {
opts = opts || {};
if (_.isString(template)) {
opts.newHTML = template;
}
templateRenderer.render(el, template, context, opts);
},
/**
* Overrides the base delegateEvents
* Binds DOM events with the view using events hash while also adding feedback event bindings
*/
delegateEvents: function() {
this.undelegateEvents(); // always undelegate events - backbone sometimes doesn't.
Backbone.View.prototype.delegateEvents.call(this);
this.__generateFeedbackBindings();
this.__generateFeedbackCellCallbacks();
_.each(this.getTrackedViews(), function(view) {
if (view.isAttachedToParent()) {
view.delegateEvents();
}
});
},
/**
* Overrides undelegateEvents
* Unbinds DOM events from the view.
*/
undelegateEvents: function() {
Backbone.View.prototype.undelegateEvents.call(this);
_.each(this.getTrackedViews(), function(view) {
view.undelegateEvents();
});
},
/**
* If detached, will replace the element passed in with this view's element and activate the view.
* @param {external:jQuery} [$el] the element to attach to. This element will be replaced with this view.
* If options.replaceMethod is provided, then this parameter is ignored.
* @param {Object} [options] optional options
* @param {Fucntion} [options.replaceMethod] if given, this view will invoke replaceMethod function
* in order to attach the view's DOM to the parent instead of calling $el.replaceWith
* @param {Booleon} [options.discardInjectionSite=false] if set to true, the injection site is not saved.
* @return {Promise} promise that when resolved, the attach process is complete. Normally this method is synchronous. Transition effects can
* make it asynchronous.
*/
attachTo: function($el, options) {
options = options || {};
var view = this;
if (!this.isAttachedToParent()) {
this.__pendingAttachInfo = {
$el: $el,
options: options
};
return this.render().done(function() {
if (!view.__attachedCallbackInvoked && view.isAttached()) {
view.__invokeAttached();
}
view.__isAttachedToParent = true;
});
}
return $.Deferred().resolve().promise();
},
/**
* Registers the view as a tracked view (defaulting as a child view), then calls view.attachTo with the element argument
* The element argument can be a String that references an element with the corresponding "inject" attribute.
* When using attachView with options.useTransition:
* Will inject a new view into an injection site by using the new view's transitionIn method. If the parent view
* previously had another view at this injections site, this previous view will be removed with that view's transitionOut.
* If this method is used within a render, the current views' injection sites will be cached so they can be transitioned out even
* though they are detached in the process of re-rendering. If no previous view is given and none can be found, the new view is transitioned in regardless.
* If the previous view is the same as the new view, it is injected normally without transitioning in.
* The previous view must has used an injection site with the standard "inject=<name of injection site>" attribute to be found.
* When the transitionIn and transitionOut methods are invoked on the new and previous views, the options parameter will be passed on to them. Other fields
* will be added to the options parameter to allow better handling of the transitions. These include:
* {
* newView: the new view
* previousView: the previous view (can be undefined)
* parentView: the parent view transitioning in or out the tracked view
* }
* @param {(external:jQuery|string)} $el the element to attach to OR the name of the injection site. The element with the attribute "inject=<name of injection site>" will be used.
* @param {View} view The instantiated view object to be attached
* @param {Object} [options] optionals options object. If using transitions, this options object will be passed on to the transitionIn and transitionOut methods as well.
* @param {boolean} [options.noActivate=false] if set to true, the view will not be activated upon attaching.
* @param {boolean} [options.shared=false] if set to true, the view will be treated as a shared view and not disposed during parent view disposing.
* @param {boolean} [options.useTransition=false] if set to true, this method will delegate attach logic to this.__transitionNewViewIntoSite
* @param {boolean} [options.addBefore=false] if true, and options.useTransition is true, the new view's element will be added before the previous view's element. Defaults to after.
* @param {View} [options.previousView] if using options.useTransition, then you can explicitly define the view that should be transitioned out.
* If using transitions and no previousView is provided, it will look to see if a view already is at this injection site and uses that by default.
* @return {Promise} resolved when all transitions are complete. No payload is provided upon resolution. If no transitions, then returns a resolved promise.
*/
attachView: function($el, view, options) {
options = options || {};
var injectionSite, injectionSiteName,
usesInjectionSiteName = _.isString($el);
if (usesInjectionSiteName) {
injectionSiteName = $el;
injectionSite = this.$('[inject=' + injectionSiteName + ']');
if (!injectionSite) {
throw 'View.attachView: No injection site found with which to attach this view. View.cid=' + this.cid;
}
} else {
injectionSite = $el;
}
if (options.useTransition) {
return this.__transitionNewViewIntoSite(injectionSiteName, view, options);
}
view.detach();
this.registerTrackedView(view, options);
view.attachTo(injectionSite, options);
if (!options.noActivate) {
view.activate();
}
return $.Deferred().resolve().promise();
},
/**
* Hook to attach all your tracked views. This hook will be called after all DOM rendering is done so injection sites should be available.
* This method can be overwritten as usual OR extended using <baseClass>.prototype.attachTrackedViews.apply(this, arguments);
* @return {Promise|Array<Promise>} you can optionally return one or more promises that when all are resolved, all tracked views are attached. Useful when using this.attachView with useTransition=true.
*/
attachTrackedViews: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Method to be invoked when the view is fully attached to the DOM (NOT just the parent). Use this method to manipulate the view
* after the DOM has been attached to the document. The default implementation is a no-op.
*/
_attached: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* @return {boolean} true if the view is attached to a parent
*/
isAttachedToParent: function() {
return this.__isAttachedToParent;
},
/**
* NOTE: depends on a global variable "document"
* @return {boolean} true if the view is attached to the DOM
*/
isAttached: function() {
return this.$el && $.contains(document, this.$el[0]);
},
/**
* If attached, will detach the view from the DOM.
* This method will only separate this view from the DOM it was attached to, but it WILL invoke the _detach
* callback on each tracked view recursively.
*/
detach: function() {
var wasAttached;
if (this.isAttachedToParent()) {
wasAttached = this.isAttached();
// Detach view from DOM
this.trigger('before-dom-detach');
if (this.injectionSite) {
this.$el.replaceWith(this.injectionSite);
this.injectionSite = undefined;
} else {
this.$el.detach();
}
if (wasAttached) {
this.__invokeDetached();
}
this.undelegateEvents();
this.__isAttachedToParent = false;
}
},
/**
* Detach all tracked views or a subset of them based on the options parameter.
* NOTE: this is not recursive - it will not separate the entire view tree.
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, detach only the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, detach only child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
*/
detachTrackedViews: function(options) {
var trackedViewsHash = this.getTrackedViews(options);
_.each(trackedViewsHash, function(view) {
view.detach();
});
},
/**
* Method to be invoked when the view is detached from the DOM (NOT just the parent). Use this method to clean up state
* after the view has been removed from the document. The default implementation is a no-op.
*/
_detached: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Resets listeners and events in order for the view to be reattached to the visible DOM
*/
activate: function() {
this.__activateTrackedViews();
if (!this.isActive()) {
this.trigger('before-activate-callback');
this._activate();
this.__isActive = true;
}
},
/**
* Method to be invoked when activate is called. Use this method to turn on any
* custom timers, listenTo's or on's that should be activatable. The default implementation is a no-op.
*/
_activate: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* @return {boolean} true if the view is active
*/
isActive: function() {
return this.__isActive;
},
/**
* Maintains view state and DOM but prevents view from becoming a zombie by removing listeners
* and events that may affect user experience. Recursively invokes deactivate on child views
*/
deactivate: function() {
this.__deactivateTrackedViews();
if (this.isActive()) {
this.trigger('before-deactivate-callback');
this._deactivate();
this.__isActive = false;
}
},
/**
* Method to be invoked when deactivate is called. Use this method to turn off any
* custom timers, listenTo's or on's that should be deactivatable. The default implementation is a no-op.
*/
_deactivate: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* Removes all listeners, disposes children views, stops listening to events, removes DOM.
* After dispose is called, the view can be safely garbage collected. Called while
* recursively removing views from the hierarchy.
*/
dispose: function() {
this.trigger('before-dispose');
this.trigger('before-dispose-callback');
this._dispose();
// Detach DOM and deactivate the view
this.detach();
this.deactivate();
// Clean up child views first
this.__disposeChildViews();
// Remove view from DOM
if (this.$el) {
this.remove();
}
// Unbind all local event bindings
this.off();
this.stopListening();
if (this.viewState) {
this.viewState.off();
this.viewState.stopListening();
}
if (this.feedbackCell) {
this.feedbackCell.off();
this.feedbackCell.stopListening();
}
// Delete the dom references
delete this.$el;
delete this.el;
this.__isDisposed = true;
this.trigger('after-dispose');
},
/**
* Method to be invoked when dispose is called. By default calling dispose will remove the
* view's element, its on's, listenTo's, and any registered children.
* Override this method to destruct any extra
*/
_dispose: function() {
// do nothing, here for overrides and to properly inform jsdoc that this is a method.
},
/**
* @return {boolean} true if the view was disposed
*/
isDisposed: function() {
return this.__isDisposed;
},
/**
* @return {boolean} true if this view has tracked views (limited by the options parameter)
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, only check the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, only check the child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
*/
hasTrackedViews: function(options) {
return !_.isEmpty(this.getTrackedViews(options));
},
/**
* Returns all tracked views, both child views and shared views.
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, get only the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, get only child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
* @return {List<View>} all tracked views (filtered by options parameter)
*/
getTrackedViews: function(options) {
return _.values(this.__getTrackedViewsHash(options));
},
/**
* @return the view with the given cid. Will look in both shared and child views.
* @param {string} viewCID the cid of the view
*/
getTrackedView: function(viewCID) {
var childView = this.__childViews[viewCID],
sharedView = this.__sharedViews[viewCID];
return childView || sharedView;
},
/**
* Binds the view as a tracked view - any recursive calls like activate, deactivate, or dispose will
* be done to the tracked view as well. Except dispose for shared views. This method defaults to register the
* view as a child view unless specified by options.shared.
* @param {View} view the tracked view
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, registers view as a shared view. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed. If false, registers view as a child view which are disposed when the parent is disposed.
* @return {View} the tracked view
*/
registerTrackedView: function(view, options) {
options = options || {};
this.unregisterTrackedView(view);
if (options.child || !options.shared) {
this.__childViews[view.cid] = view;
} else {
this.__sharedViews[view.cid] = view;
}
return view;
},
/**
* Unbinds the tracked view - no recursive calls will be made to this shared view
* @param {View} view the shared view
* @return {View} the tracked view
*/
unregisterTrackedView: function(view) {
delete this.__childViews[view.cid];
delete this.__sharedViews[view.cid];
return view;
},
/**
* Unbinds all tracked view - no recursive calls will be made to this shared view
* You can limit the types of views that will be unregistered by using the options parameter.
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, unregister only the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, unregister only child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
* @return {View} the tracked view
*/
unregisterTrackedViews: function(options) {
var trackedViewsHash = this.getTrackedViews(options);
_.each(trackedViewsHash, function(view) {
this.unregisterTrackedView(view, options);
}, this);
},
/**
* Override to provide your own transition out logic. Default logic is to just detach from the page.
* The method is passed a callback that should be invoked when the transition out has fully completed.
* @param {Function} done callback that MUST be invoked when the transition is complete.
* @param options optionals options object
* @param {View} options.currentView the view that is being transitioned in.
* @param {View} options.previousView the view that is being transitioned out. Typically this view.
* @param {View} options.parentView the view that is invoking the transition.
*/
transitionOut: function(done, options) {
this.detach();
done();
},
/**
* Override to provide your own transition in logic. Default logic is to just attach to the page.
* The method is passed a callback that should be invoked when the transition in has fully completed.
* @param {Function} attach callback to be invoked when you want this view to be attached to the dom.
If you are trying to transition in a tracked view, consider using this.transitionInView()
* @param {Function} done callback that MUST be invoked when the transition is complete.
* @param options optionals options object
* @param {View} options.currentView the view that is being transitioned in.
* @param {View} options.previousView the view that is being transitioned out. Typically this view.
* @param {View} options.parentView the view that is invoking the transition.
*/
transitionIn: function(attach, done, options) {
attach();
done();
},
/**
* Invokes a feedback entry's "then" method
* @param {string} to the "to" field corresponding to the feedback entry to be invoked.
* @param {Event} [evt] the event to be passed to the "then" method
* @param {Object} [indexMap] a map from index variable name to index value. Needed for "to" fields with array notation.
*/
invokeFeedback: function(to, evt, indexMap) {
var result,
feedbackToInvoke = _.find(this.feedback, function(feedback) {
var toToCheck = feedback.to;
if (_.isArray(toToCheck)) {
return _.contains(toToCheck, to);
} else {
return to === toToCheck;
}
}),
feedbackCellField = to;
if (feedbackToInvoke) {
if (indexMap) {
feedbackCellField = this.__substituteIndicesUsingMap(to, indexMap);
}
result = feedbackToInvoke.then.call(this, evt, indexMap);
this.__processFeedbackThenResult(result, feedbackCellField);
}
},
//************** Private methods **************//
/**
* Attaches views using this.injectionSites. The API for injectionSites looks like:
* injectionSites: {
* foo: fooView, // foo is injectionSite, fooView is the view
bar: 'barView', // bar is injectionSite, 'barView' is a field on the view (view.barView)
baz: function() { // baz is injectionSite
return this.bazView; // the context 'this' is the view
},
taz: { // if you want to pass in options, use a config object with 'view' and 'options'
view: (same as the three above: direct reference, string of view field, or function that return view),
options: {} // optional options
}
* }
* To create dynamic show/hide logic, perform the logic in a function that returns the correct view, or you can
* call this.set('hide:foo', true) or this.set('hide:foo', false)
* @private
*/
__attachViewsFromInjectionSites: function() {
var injectionSites = _.result(this, 'injectionSites');
_.each(injectionSites, function(config, injectionSiteName) {
if (!this.get('hide:' + injectionSiteName)) {
var options = {};
var trackedView;
if (_.isFunction(config)) {
config = config.call(this);
}
if (config instanceof Backbone.View) {
trackedView = config;
} else if (_.isObject(config)) {
options = config.options;
config = config.view;
}
if (!trackedView) {
if (_.isString(config)) {
trackedView = _.result(this, config);
} else if (config instanceof Backbone.View) {
trackedView = config;
} else if (_.isFunction(config)) {
trackedView = config.call(this);
}
}
if (trackedView) {
this.attachView(injectionSiteName, trackedView, options);
}
}
}, this);
},
/**
* Parses the combined arrays from the defaultPrepareFields array and the prepareFields array (or function
* returning an array).
*
* The default prepared fields are: [ { name: 'view', value: 'viewState' }, 'model' ]
*
* Prepared fields can be defined in a couple of ways:
* preparedFields = [
* 'model',
* { name: 'app', value: someGlobalCell },
* 'a value that does not exist on the view',
* { name: 'view', value: 'viewState' },
* { name: 'patientId', value: '_patientId' },
* { name: 'calculatedValue', value: function() { return 'calculated: ' + this.viewProperty },
* 'objectWithoutToJSON'
* ]
*
* Will result in the following context (where this === this view and it assumes all the properties on the view
* that are referenced are defined):
* {
* model: this.model.toJSON(),
* app: someGlobalCell.toJSON(),
* view: this.viewState.toJSON(),
* patientId: this._patientId,
* calculatedValue: 'calculated: ' + this.viewProperty,
* objectWithoutToJSON: this.objectWithoutToJSON
* }
*
* Note: alternatively, you can define your prepareFields as an object that will be mapped to an array of { name: key, value: value }
*
* Things to be careful of:
* * If the view already has a field named 'someGlobalCell' then the property on the view will be used instead of the global value.
* * if the prepared field item is not a string or object containing 'name' and 'value' properties, then an exception
* will be thrown.
* * 'model' and 'view' are reserved field names and cannot be reused.
*
* @return {Object} context composed of { modelName: model.toJSON() } for every model identified.
* @private
*/
__getPrepareFieldsContext: function() {
var prepareFieldsContext = {};
var prepareFields = _.result(this, 'prepareFields');
if (prepareFields && _.isObject(prepareFields) && !_.isArray(prepareFields)) {
var keys = _.keys(prepareFields);
prepareFields = _.map(keys, function(key) {
return { name: key, value: prepareFields[key] };
});
}
var defaultPrepareFields = [ { name: 'view', value: 'viewState' }, 'model' ];
prepareFields = _.union(prepareFields, defaultPrepareFields);
if (prepareFields && prepareFields.length > 0) {
for (var fieldIndex = 0; fieldIndex < prepareFields.length; fieldIndex++) {
var prepareField = prepareFields[fieldIndex];
var prepareFieldIsSimpleString = _.isString(prepareField);
var prepareFieldName = prepareField;
var prepareFieldValue = prepareField;
if (!prepareFieldIsSimpleString) {
if (!_.isString(prepareField.name)) {
throw "prepareFields items need to either be a string or define a .name property that is a simple string to use for the key in the template context.";
}
if (_.isUndefined(prepareField.value)) {
throw "prepareFields items need a value property if it is not a string.";
}
prepareFieldName = prepareField.name;
prepareFieldValue = prepareField.value;
}
if (!_.isUndefined(prepareFieldsContext[prepareFieldName])) {
throw "duplicate prepareFields name (" + prepareFieldName + "). Note 'view' and 'model' are reserved names.";
}
var prepareFieldValueIsDefinedOnView = false;
if (_.isFunction(prepareFieldValue)) {
prepareFieldValue = prepareFieldValue.call(this);
} else {
// Note _.result() also returns undefined if the 2nd argument is not a string.
var prepareFieldValueFromView = _.result(this, prepareFieldValue);
prepareFieldValueIsDefinedOnView = !_.isUndefined(prepareFieldValueFromView);
if (prepareFieldValueIsDefinedOnView) {
prepareFieldValue = prepareFieldValueFromView;
}
}
if (prepareFieldValue && _.isFunction(prepareFieldValue.toJSON)) {
prepareFieldsContext[prepareFieldName] = prepareFieldValue.toJSON();
} else if (!prepareFieldIsSimpleString || prepareFieldValueIsDefinedOnView) {
prepareFieldsContext[prepareFieldName] = prepareFieldValue;
}
}
}
var context = this._prepare(prepareFieldsContext);
if (_.isUndefined(context)) {
context = prepareFieldsContext;
} else {
context = _.extend(prepareFieldsContext, context);
}
return context;
},
/**
* Initializes the behaviors
* @private
*/
__initializeBehaviors: function(viewOptions) {
var view = this;
if (!_.isEmpty(this.behaviors)) {
view.__behaviorInstances = {};
_.each(this.behaviors, function(behaviorDefinition, alias) {
if (!_.has(behaviorDefinition, 'behavior')) {
behaviorDefinition = {behavior: behaviorDefinition};
}
var BehaviorClass = behaviorDefinition.behavior;
if (!(BehaviorClass && _.isFunction(BehaviorClass))) {
throw new Error('Incorrect behavior definition. Expected key "behavior" to be a class but instead got ' +
String(BehaviorClass));
}
var behaviorOptions = _.pick(behaviorDefinition, function(value, key) {
return key !== 'behavior';
});
behaviorOptions.view = view;
behaviorOptions.alias = alias;
var behaviorAttributes = behaviorDefinition.attributes || {};
var behaviorInstance = view.__behaviorInstances[alias] = new BehaviorClass(behaviorAttributes, behaviorOptions, viewOptions);
// Add the behavior's mixin fields to the view's public API
if (behaviorInstance.mixin) {
var mixin = _.result(behaviorInstance, 'mixin');
_.each(mixin, function(field, fieldName) {
// Default to a view's field over a behavior mixin
if (_.isUndefined(view[fieldName])) {
if (_.isFunction(field)) {
// Behavior mixin functions will be behavior-scoped - the context will be the behavior.
view[fieldName] = _.bind(field, behaviorInstance);
} else {
view[fieldName] = field;
}
}
});
}
});
}
},
/**
* If the view is attaching during the render process, then it replaces the injection site
* with the view's element after the view has generated its DOM.
* @private
*/
__performPendingAttach: function() {
this.trigger('before-dom-attach');
this.__replaceInjectionSite(this.__pendingAttachInfo.$el, this.__pendingAttachInfo.options);
delete this.__pendingAttachInfo;
},
/**
* Deactivates all tracked views or a subset of them based on the options parameter.
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, deactivate only the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, deactivate only child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
* @private
*/
__deactivateTrackedViews: function(options) {
_.each(this.getTrackedViews(options), function(view) {
view.deactivate();
});
},
/**
* Activates all tracked views or a subset of them based on the options parameter.
* @param {Object} [options={}] Optional options.
* @param {boolean} [options.shared=false] If true, activate only the shared views. These are views not owned by this parent. As compared to a child view
* which are disposed when the parent is disposed.
* @param {boolean} [options.child=false] If true, activate only child views. These are views that are owned by the parent and dispose of them if the parent is disposed.
* @private
*/
__activateTrackedViews: function(options) {
_.each(this.getTrackedViews(options), function(view) {
view.activate();
});
},
/**
* Disposes all child views recursively
* @private
*/
__disposeChildViews: function() {
_.each(this.__childViews, function(view) {
view.dispose();
});
},
/**
* Will inject a new view into an injection site by using the new view's transitionIn method. If the parent view
* previously had another view at this injections site, this previous view will be removed with that view's transitionOut.
* If this method is used within a render, the current views' injection sites will be cached so they can be transitioned out even
* though they are detached in the process of re-rendering. If no previous view is given and none can be found, the new view is transitioned in regardless.
* If the previous view is the same as the new view, it is injected normally without transitioning in.
* The previous view must has used an injection site with the standard "inject=<name of injection site>" attribute to be found.
* @private
* @param {string} injectionSiteName The name of the injection site in the template. This is the value corresponding to the attribute "inject".
* @param {View} newView The instantiated view object to be transitioned into the injection site
* @param {Object} [options] optional options object. This options object will be passed on to the transitionIn and transitionOut methods as well.
* @param {View} [options.previousView] the view that should be transitioned out. If none is provided, it will look to see if a view already
* is at this injection site and uses that by default.
* @param {boolean} [options.addBefore=false] if true, the new view's element will be added before the previous view's element. Defaults to after.
* @param {boolean} [options.shared=false] if set to true, the view will be treated as a shared view and not disposed during parent view disposing.
* @return {Promise} resolved when all transitions are complete. No payload is provided upon resolution.
* When the transitionIn and transitionOut methods are invoked on the new and previous views, the options parameter will be passed on to them. Other fields
* will be added to the options parameter to allow better handling of the transitions. These include:
* {
* newView: the new view
* previousView: the previous view (can be undefined)
* parentView: the parent view transitioning in or out the tracked view
* }
*/
__transitionNewViewIntoSite: function(injectionSiteName, newView, options) {
var previousView, injectionSite;