forked from marionettejs/backbone.marionette
/
backbone.marionette.js
1490 lines (1206 loc) · 43.4 KB
/
backbone.marionette.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Backbone.Marionette, v1.0.0-beta1
// Copyright (c)2012 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
// http://github.com/marionettejs/backbone.marionette
Backbone.Marionette = Marionette = (function(Backbone, _, $){
var Marionette = {};
// Helpers
// -------
// For slicing `arguments` in functions
var slice = Array.prototype.slice;
// Borrow the Backbone `extend` method so we can use it as needed
Marionette.extend = Backbone.Model.extend;
// Trigger an event and a corresponding method name. Examples:
//
// `this.triggerMethod("foo")` will trigger the "foo" event and
// call the "onFoo" method.
//
// `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
// call the "onFooBar" method.
Marionette.triggerMethod = function(){
var args = Array.prototype.slice.apply(arguments);
var eventName = args[0];
var segments = eventName.split(":");
var segment, capLetter, methodName = "on";
for (var i = 0; i < segments.length; i++){
segment = segments[i];
capLetter = segment.charAt(0).toUpperCase();
methodName += capLetter + segment.slice(1);
}
this.trigger.apply(this, arguments);
if (_.isFunction(this[methodName])){
args.shift();
this[methodName].apply(this, args);
}
};
// EventBinder
// -----------
// Import the event binder from it's new home
// https://github.com/marionettejs/backbone.eventbinder
Marionette.EventBinder = Backbone.EventBinder;
// Add the EventBinder methods to the view directly,
// but keep them bound to the EventBinder instance so they work properly.
// This allows the event binder's implementation to vary independently
// of it being attached to the view... for example the internal structure
// used to store the events can change without worry about it interfering
// with Marionette's views.
Marionette.addEventBinder = function(target){
var eventBinder = new Marionette.EventBinder();
target.eventBinder = eventBinder;
target.bindTo = _.bind(eventBinder.bindTo, eventBinder);
target.unbindFrom = _.bind(eventBinder.unbindFrom, eventBinder);
target.unbindAll = _.bind(eventBinder.unbindAll, eventBinder);
};
// Marionette.View
// ---------------
// The core view type that other Marionette views extend from.
Marionette.View = Backbone.View.extend({
constructor: function(){
_.bindAll(this, "render");
Marionette.addEventBinder(this);
Backbone.View.prototype.constructor.apply(this, arguments);
this.bindBackboneEntityTo(this.model, this.modelEvents);
this.bindBackboneEntityTo(this.collection, this.collectionEvents);
this.bindTo(this, "show", this.onShowCalled, this);
},
// import the "triggerMethod" to trigger events with corresponding
// methods if the method exists
triggerMethod: Marionette.triggerMethod,
// Get the template for this view
// instance. You can set a `template` attribute in the view
// definition or pass a `template: "whatever"` parameter in
// to the constructor options.
getTemplate: function(){
var template;
// Get the template from `this.options.template` or
// `this.template`. The `options` takes precedence.
if (this.options && this.options.template){
template = this.options.template;
} else {
template = this.template;
}
return template;
},
// Mix in template helper methods. Looks for a
// `templateHelpers` attribute, which can either be an
// object literal, or a function that returns an object
// literal. All methods and attributes from this object
// are copies to the object passed in.
mixinTemplateHelpers: function(target){
target = target || {};
var templateHelpers = this.templateHelpers;
if (_.isFunction(templateHelpers)){
templateHelpers = templateHelpers.call(this);
}
return _.extend(target, templateHelpers);
},
// Configure `triggers` to forward DOM events to view
// events. `triggers: {"click .foo": "do:foo"}`
configureTriggers: function(){
if (!this.triggers) { return; }
var triggers = this.triggers;
var that = this;
var triggerEvents = {};
// Allow `triggers` to be configured as a function
if (_.isFunction(triggers)){ triggers = triggers.call(this); }
// Configure the triggers, prevent default
// action and stop propagation of DOM events
_.each(triggers, function(value, key){
triggerEvents[key] = function(e){
if (e && e.preventDefault){ e.preventDefault(); }
if (e && e.stopPropagation){ e.stopPropagation(); }
that.trigger(value);
};
});
return triggerEvents;
},
// Overriding Backbone.View's delegateEvents specifically
// to handle the `triggers` configuration
delegateEvents: function(events){
events = events || this.events;
if (_.isFunction(events)){ events = events.call(this); }
var combinedEvents = {};
var triggers = this.configureTriggers();
_.extend(combinedEvents, events, triggers);
Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
},
// Internal method, handles the `show` event.
onShowCalled: function(){},
// Default `close` implementation, for removing a view from the
// DOM and unbinding it. Regions will call this method
// for you. You can specify an `onClose` method in your view to
// add custom code that is called after the view is closed.
close: function(){
if (this.isClosed) { return; }
this.triggerMethod("before:close");
this.remove();
this.unbindAll();
this.triggerMethod("close");
this.isClosed = true;
},
// This method binds the elements specified in the "ui" hash inside the view's code with
// the associated jQuery selectors.
bindUIElements: function(){
if (!this.ui) { return; }
var that = this;
if (!this.uiBindings) {
// We want to store the ui hash in uiBindings, since afterwards the values in the ui hash
// will be overridden with jQuery selectors.
this.uiBindings = this.ui;
}
// refreshing the associated selectors since they should point to the newly rendered elements.
this.ui = {};
_.each(_.keys(this.uiBindings), function(key) {
var selector = that.uiBindings[key];
that.ui[key] = that.$(selector);
});
},
// This method is used to bind a backbone "entity" (collection/model) to methods on the view.
bindBackboneEntityTo: function(entity, bindings){
if (!entity || !bindings) { return; }
var view = this;
_.each(bindings, function(methodName, evt){
var method = view[methodName];
if(!method) {
throw new Error("View method '"+ methodName +"' was configured as an event handler, but does not exist.");
}
view.bindTo(entity, evt, method, view);
});
}
});
// Item View
// ---------
// A single item view implementation that contains code for rendering
// with underscore.js templates, serializing the view's model or collection,
// and calling several methods on extended views, such as `onRender`.
Marionette.ItemView = Marionette.View.extend({
constructor: function(){
Marionette.View.prototype.constructor.apply(this, arguments);
if (this.initialEvents){
this.initialEvents();
}
},
// Serialize the model or collection for the view. If a model is
// found, `.toJSON()` is called. If a collection is found, `.toJSON()`
// is also called, but is used to populate an `items` array in the
// resulting data. If both are found, defaults to the model.
// You can override the `serializeData` method in your own view
// definition, to provide custom serialization for your view's data.
serializeData: function(){
var data;
if (this.model) {
data = this.model.toJSON();
}
else if (this.collection) {
data = { items: this.collection.toJSON() };
}
data = this.mixinTemplateHelpers(data);
return data;
},
// Render the view, defaulting to underscore.js templates.
// You can override this in your view definition to provide
// a very specific rendering for your view. In general, though,
// you should override the `Marionette.Renderer` object to
// change how Marionette renders views.
render: function(){
this.isClosed = false;
this.triggerMethod("before:render", this);
this.triggerMethod("item:before:render", this);
var data = this.serializeData();
var template = this.getTemplate();
var html = Marionette.Renderer.render(template, data);
this.$el.html(html);
this.bindUIElements();
this.triggerMethod("render", this);
this.triggerMethod("item:rendered", this);
return this;
},
// Override the default close event to add a few
// more events that are triggered.
close: function(){
if (this.isClosed){ return; }
this.triggerMethod('item:before:close');
Marionette.View.prototype.close.apply(this, arguments);
this.triggerMethod('item:closed');
}
});
// Collection View
// ---------------
// A view that iterates over a Backbone.Collection
// and renders an individual ItemView for each model.
Marionette.CollectionView = Marionette.View.extend({
constructor: function(){
this.initChildViewStorage();
Marionette.View.prototype.constructor.apply(this, arguments);
this.initialEvents();
this.onShowCallbacks = new Marionette.Callbacks();
},
// Configured the initial events that the collection view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "add", this.addChildView, this);
this.bindTo(this.collection, "remove", this.removeItemView, this);
this.bindTo(this.collection, "reset", this.render, this);
}
},
// Handle a child item added to the collection
addChildView: function(item, collection, options){
this.closeEmptyView();
var ItemView = this.getItemView(item);
var index;
if(options && options.index){
index = options.index;
} else {
index = 0;
}
return this.addItemView(item, ItemView, index);
},
// Override from `Marionette.View` to guarantee the `onShow` method
// of child views is called.
onShowCalled: function(){
this.onShowCallbacks.run();
},
// Internal method to trigger the before render callbacks
// and events
triggerBeforeRender: function(){
this.triggerMethod("before:render", this);
this.triggerMethod("collection:before:render", this);
},
// Internal method to trigger the rendered callbacks and
// events
triggerRendered: function(){
this.triggerMethod("render", this);
this.triggerMethod("collection:rendered", this);
},
// Render the collection of items. Override this method to
// provide your own implementation of a render function for
// the collection view.
render: function(){
this.isClosed = false;
this.triggerBeforeRender();
this.closeEmptyView();
this.closeChildren();
if (this.collection && this.collection.length > 0) {
this.showCollection();
} else {
this.showEmptyView();
}
this.triggerRendered();
return this;
},
// Internal method to loop through each item in the
// collection view and show it
showCollection: function(){
var that = this;
var ItemView;
this.collection.each(function(item, index){
ItemView = that.getItemView(item);
that.addItemView(item, ItemView, index);
});
},
// Internal method to show an empty view in place of
// a collection of item views, when the collection is
// empty
showEmptyView: function(){
var EmptyView = this.options.emptyView || this.emptyView;
if (EmptyView && !this._showingEmptyView){
this._showingEmptyView = true;
var model = new Backbone.Model();
this.addItemView(model, EmptyView, 0);
}
},
// Internal method to close an existing emptyView instance
// if one exists. Called when a collection view has been
// rendered empty, and then an item is added to the collection.
closeEmptyView: function(){
if (this._showingEmptyView){
this.closeChildren();
delete this._showingEmptyView;
}
},
// Retrieve the itemView type, either from `this.options.itemView`
// or from the `itemView` in the object definition. The "options"
// takes precedence.
getItemView: function(item){
var itemView = this.options.itemView || this.itemView;
if (!itemView){
var err = new Error("An `itemView` must be specified");
err.name = "NoItemViewError";
throw err;
}
return itemView;
},
// Render the child item's view and add it to the
// HTML for the collection view.
addItemView: function(item, ItemView, index){
var that = this;
var view = this.buildItemView(item, ItemView);
// Store the child view itself so we can properly
// remove and/or close it later
this.storeChild(view);
this.triggerMethod("item:added", view);
// Render it and show it
var renderResult = this.renderItemView(view, index);
// call onShow for child item views
if (view.onShow){
this.onShowCallbacks.add(view.onShow, view);
}
// Forward all child item view events through the parent,
// prepending "itemview:" to the event name
var childBinding = this.bindTo(view, "all", function(){
var args = slice.call(arguments);
args[0] = "itemview:" + args[0];
args.splice(1, 0, view);
that.triggerMethod.apply(that, args);
});
// Store all child event bindings so we can unbind
// them when removing / closing the child view
this.childBindings = this.childBindings || {};
this.childBindings[view.cid] = childBinding;
return renderResult;
},
// render the item view
renderItemView: function(view, index) {
view.render();
this.appendHtml(this, view, index);
},
// Build an `itemView` for every model in the collection.
buildItemView: function(item, ItemView){
var itemViewOptions;
if (_.isFunction(this.itemViewOptions)){
itemViewOptions = this.itemViewOptions(item);
} else {
itemViewOptions = this.itemViewOptions;
}
var options = _.extend({model: item}, itemViewOptions);
var view = new ItemView(options);
return view;
},
// Remove the child view and close it
removeItemView: function(item){
var view = this.children[item.cid];
if (view){
var childBinding = this.childBindings[view.cid];
if (childBinding) {
this.unbindFrom(childBinding);
delete this.childBindings[view.cid];
}
view.close();
delete this.children[item.cid];
}
if (!this.collection || this.collection.length === 0){
this.showEmptyView();
}
this.triggerMethod("item:removed", view);
},
// Append the HTML to the collection's `el`.
// Override this method to do something other
// then `.append`.
appendHtml: function(collectionView, itemView, index){
collectionView.$el.append(itemView.el);
},
// Store references to all of the child `itemView`
// instances so they can be managed and cleaned up, later.
storeChild: function(view){
this.children[view.model.cid] = view;
},
// Internal method to set up the `children` object for
// storing all of the child views
initChildViewStorage: function(){
this.children = {};
},
// Handle cleanup and other closing needs for
// the collection of views.
close: function(){
if (this.isClosed){ return; }
this.triggerMethod("collection:before:close");
this.closeChildren();
this.triggerMethod("collection:closed");
Marionette.View.prototype.close.apply(this, arguments);
},
// Close the child views that this collection view
// is holding on to, if any
closeChildren: function(){
var that = this;
if (this.children){
_.each(_.clone(this.children), function(childView){
that.removeItemView(childView.model);
});
}
}
});
// Composite View
// --------------
// Used for rendering a branch-leaf, hierarchical structure.
// Extends directly from CollectionView and also renders an
// an item view as `modelView`, for the top leaf
Marionette.CompositeView = Marionette.CollectionView.extend({
constructor: function(options){
Marionette.CollectionView.apply(this, arguments);
this.itemView = this.getItemView();
},
// Configured the initial events that the composite view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "add", this.addChildView, this);
this.bindTo(this.collection, "remove", this.removeItemView, this);
this.bindTo(this.collection, "reset", this.renderCollection, this);
}
},
// Retrieve the `itemView` to be used when rendering each of
// the items in the collection. The default is to return
// `this.itemView` or Marionette.CompositeView if no `itemView`
// has been defined
getItemView: function(item){
var itemView = this.options.itemView || this.itemView || this.constructor;
if (!itemView){
var err = new Error("An `itemView` must be specified");
err.name = "NoItemViewError";
throw err;
}
return itemView;
},
// Serialize the collection for the view.
// You can override the `serializeData` method in your own view
// definition, to provide custom serialization for your view's data.
serializeData: function(){
var data = {};
if (this.model){
data = this.model.toJSON();
}
data = this.mixinTemplateHelpers(data);
return data;
},
// Renders the model once, and the collection once. Calling
// this again will tell the model's view to re-render itself
// but the collection will not re-render.
render: function(){
this.isClosed = false;
this.resetItemViewContainer();
var html = this.renderModel();
this.$el.html(html);
// the ui bindings is done here and not at the end of render since they
// will not be available until after the model is rendered, but should be
// available before the collection is rendered.
this.bindUIElements();
this.triggerMethod("composite:model:rendered");
this.triggerMethod("render");
this.renderCollection();
this.triggerMethod("composite:rendered");
return this;
},
// Render the collection for the composite view
renderCollection: function(){
Marionette.CollectionView.prototype.render.apply(this, arguments);
this.triggerMethod("composite:collection:rendered");
},
// Render an individual model, if we have one, as
// part of a composite view (branch / leaf). For example:
// a treeview.
renderModel: function(){
var data = {};
data = this.serializeData();
var template = this.getTemplate();
return Marionette.Renderer.render(template, data);
},
// Appends the `el` of itemView instances to the specified
// `itemViewContainer` (a jQuery selector). Override this method to
// provide custom logic of how the child item view instances have their
// HTML appended to the composite view instance.
appendHtml: function(cv, iv){
var $container = this.getItemViewContainer(cv);
$container.append(iv.el);
},
// Internal method to ensure an `$itemViewContainer` exists, for the
// `appendHtml` method to use.
getItemViewContainer: function(containerView){
if ("$itemViewContainer" in containerView){
return containerView.$itemViewContainer;
}
var container;
if (containerView.itemViewContainer){
var selector = _.result(containerView, "itemViewContainer");
container = containerView.$(selector);
if (container.length <= 0) {
var err = new Error("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer);
err.name = "ItemViewContainerMissingError";
throw err;
}
} else {
container = containerView.$el;
}
containerView.$itemViewContainer = container;
return container;
},
// Internal method to reset the `$itemViewContainer` on render
resetItemViewContainer: function(){
if (this.$itemViewContainer){
delete this.$itemViewContainer;
}
}
});
// Region
// ------
//
// Manage the visual regions of your composite application. See
// http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
Marionette.Region = function(options){
this.options = options || {};
var el = this.options.el;
delete this.options.el;
Marionette.addEventBinder(this);
if (el){
this.el = el;
}
if (!this.el){
var err = new Error("An 'el' must be specified for a region.");
err.name = "NoElError";
throw err;
}
if (this.initialize){
this.initialize.apply(this, arguments);
}
};
// Region Type methods
// -------------------
_.extend(Marionette.Region, {
// Build an instance of a region by passing in a configuration object
// and a default region type to use if none is specified in the config.
//
// The config object should either be a string as a jQuery DOM selector,
// a Region type directly, or an object literal that specifies both
// a selector and regionType:
//
// ```js
// {
// selector: "#foo",
// regionType: MyCustomRegion
// }
// ```
//
buildRegion: function(regionConfig, defaultRegionType){
var regionIsString = (typeof regionConfig === "string");
var regionSelectorIsString = (typeof regionConfig.selector === "string");
var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
var regionIsType = (typeof regionConfig === "function");
if (!regionIsType && !regionIsString && !regionSelectorIsString) {
throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
}
var selector, RegionType;
// get the selector for the region
if (regionIsString) {
selector = regionConfig;
}
if (regionConfig.selector) {
selector = regionConfig.selector;
}
// get the type for the region
if (regionIsType){
RegionType = regionConfig;
}
if (!regionIsType && regionTypeIsUndefined) {
RegionType = defaultRegionType;
}
if (regionConfig.regionType) {
RegionType = regionConfig.regionType;
}
// build the region instance
var regionManager = new RegionType({
el: selector
});
return regionManager;
}
});
// Region Instance Methods
// -----------------------
_.extend(Marionette.Region.prototype, Backbone.Events, {
// Displays a backbone view instance inside of the region.
// Handles calling the `render` method for you. Reads content
// directly from the `el` attribute. Also calls an optional
// `onShow` and `close` method on your view, just after showing
// or just before closing the view, respectively.
show: function(view){
this.ensureEl();
this.close();
view.render();
this.open(view);
if (view.onShow) { view.onShow(); }
view.trigger("show");
if (this.onShow) { this.onShow(view); }
this.trigger("view:show", view);
this.currentView = view;
},
ensureEl: function(){
if (!this.$el || this.$el.length === 0){
this.$el = this.getEl(this.el);
}
},
// Override this method to change how the region finds the
// DOM element that it manages. Return a jQuery selector object.
getEl: function(selector){
return $(selector);
},
// Override this method to change how the new view is
// appended to the `$el` that the region is managing
open: function(view){
this.$el.html(view.el);
},
// Close the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
close: function(){
var view = this.currentView;
if (!view || view.isClosed){ return; }
if (view.close) { view.close(); }
this.trigger("view:closed", view);
delete this.currentView;
},
// Attach an existing view to the region. This
// will not call `render` or `onShow` for the new view,
// and will not replace the current HTML for the `el`
// of the region.
attachView: function(view){
this.currentView = view;
},
// Reset the region by closing any existing view and
// clearing out the cached `$el`. The next time a view
// is shown via this region, the region will re-query the
// DOM for the region's `el`.
reset: function(){
this.close();
delete this.$el;
}
});
// Copy the `extend` function used by Backbone's classes
Marionette.Region.extend = Marionette.extend;
// Layout
// ------
// Used for managing application layouts, nested layouts and
// multiple regions within an application or sub-application.
//
// A specialized view type that renders an area of HTML and then
// attaches `Region` instances to the specified `regions`.
// Used for composite view management and sub-application areas.
Marionette.Layout = Marionette.ItemView.extend({
regionType: Marionette.Region,
// Ensure the regions are avialable when the `initialize` method
// is called.
constructor: function () {
this.initializeRegions();
Backbone.Marionette.ItemView.apply(this, arguments);
},
// Layout's render will use the existing region objects the
// first time it is called. Subsequent calls will close the
// views that the regions are showing and then reset the `el`
// for the regions to the newly rendered DOM elements.
render: function(){
// If this is not the first render call, then we need to
// re-initializing the `el` for each region
if (!this._firstRender){
this.closeRegions();
this.reInitializeRegions();
} else {
this._firstRender = false;
}
var result = Marionette.ItemView.prototype.render.apply(this, arguments);
return result;
},
// Handle closing regions, and then close the view itself.
close: function () {
if (this.isClosed){ return; }
this.closeRegions();
this.destroyRegions();
Backbone.Marionette.ItemView.prototype.close.call(this, arguments);
},
// Initialize the regions that have been defined in a
// `regions` attribute on this layout. The key of the
// hash becomes an attribute on the layout object directly.
// For example: `regions: { menu: ".menu-container" }`
// will product a `layout.menu` object which is a region
// that controls the `.menu-container` DOM element.
initializeRegions: function () {
if (!this.regionManagers){
this.regionManagers = {};
}
var that = this;
var regions = this.regions || {};
_.each(regions, function (region, name) {
var regionManager = Marionette.Region.buildRegion(region, that.regionType);
regionManager.getEl = function(selector){
return that.$(selector);
};
that.regionManagers[name] = regionManager;
that[name] = regionManager;
});
},
// Re-initialize all of the regions by updating the `el` that
// they point to
reInitializeRegions: function(){
if (this.regionManagers && _.size(this.regionManagers)===0){
this.initializeRegions();
} else {
_.each(this.regionManagers, function(region){
region.reset();
});
}
},
// Close all of the regions that have been opened by
// this layout. This method is called when the layout
// itself is closed.
closeRegions: function () {
var that = this;
_.each(this.regionManagers, function (manager, name) {
manager.close();
});
},
// Destroys all of the regions by removing references
// from the Layout
destroyRegions: function(){
var that = this;
_.each(this.regionManagers, function (manager, name) {
delete that[name];
});
this.regionManagers = {};
}
});
// Application
// -----------
// Contain and manage the composite application as a whole.
// Stores and starts up `Region` objects, includes an
// event aggregator as `app.vent`
Marionette.Application = function(options){
this.initCallbacks = new Marionette.Callbacks();
this.vent = new Marionette.EventAggregator();
this.commands = new Backbone.Wreqr.Commands();
this.reqres = new Backbone.Wreqr.RequestResponse();
this.submodules = {};
_.extend(this, options);
Marionette.addEventBinder(this);
};
_.extend(Marionette.Application.prototype, Backbone.Events, {
// Command execution, facilitated by Backbone.Wreqr.Commands
execute: function(){
this.commands.execute.apply(this.commands, arguments);
},
// Request/response, facilitated by Backbone.Wreqr.RequestResponse
request: function(){
return this.reqres.request.apply(this.reqres, arguments);
},
// Add an initializer that is either run at when the `start`
// method is called, or run immediately if added after `start`
// has already been called.
addInitializer: function(initializer){
this.initCallbacks.add(initializer);
},
// kick off all of the application's processes.
// initializes all of the regions that have been added
// to the app, and runs all of the initializer functions
start: function(options){
this.trigger("initialize:before", options);
this.initCallbacks.run(options, this);
this.trigger("initialize:after", options);
this.trigger("start", options);
},
// Add regions to your app.