This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone.marionette.js
2111 lines (1691 loc) · 61.6 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
var Marionette = (function(global, Backbone, _){
"use strict";
// Define and export the Marionette namespace
var Marionette = {};
Backbone.Marionette = Marionette;
// Get the DOM manipulator for later use
Marionette.$ = Backbone.$;
// Helpers
// -------
// For slicing `arguments` in functions
var protoSlice = Array.prototype.slice;
function slice(args) {
return protoSlice.call(args);
}
function throwError(message, name) {
var error = new Error(message);
error.name = name || 'Error';
throw error;
}
// Marionette.extend
// -----------------
// Borrow the Backbone `extend` method so we can use it as needed
Marionette.extend = Backbone.Model.extend;
// Marionette.getOption
// --------------------
// Retrieve an object, function or other value from a target
// object or its `options`, with `options` taking precedence.
Marionette.getOption = function(target, optionName){
if (!target || !optionName){ return; }
var value;
if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
value = target.options[optionName];
} else {
value = target[optionName];
}
return value;
};
// Marionette.normalizeMethods
// ----------------------
// Pass in a mapping of events => functions or function names
// and return a mapping of events => functions
Marionette.normalizeMethods = function(hash) {
var normalizedHash = {}, method;
_.each(hash, function(fn, name) {
method = fn;
if (!_.isFunction(method)) {
method = this[method];
}
if (!method) {
return;
}
normalizedHash[name] = method;
}, this);
return normalizedHash;
};
// Trigger an event and/or 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(){
// split the event name on the ":"
var splitter = /(^|:)(\w)/gi;
// take the event section ("section1:section2:section3")
// and turn it in to uppercase name
function getEventName(match, prefix, eventName) {
return eventName.toUpperCase();
}
// actual triggerMethod implementation
var triggerMethod = function(event) {
// get the method name from the event name
var methodName = 'on' + event.replace(splitter, getEventName);
var method = this[methodName];
// trigger the event, if a trigger method exists
if(_.isFunction(this.trigger)) {
this.trigger.apply(this, arguments);
}
// call the onMethodName if it exists
if (_.isFunction(method)) {
// pass all arguments, except the event name
return method.apply(this, _.tail(arguments));
}
};
return triggerMethod;
})();
// DOMRefresh
// ----------
//
// Monitor a view's state, and after it has been rendered and shown
// in the DOM, trigger a "dom:refresh" event every time it is
// re-rendered.
Marionette.MonitorDOMRefresh = (function(documentElement){
// track when the view has been shown in the DOM,
// using a Marionette.Region (or by other means of triggering "show")
function handleShow(view){
view._isShown = true;
triggerDOMRefresh(view);
}
// track when the view has been rendered
function handleRender(view){
view._isRendered = true;
triggerDOMRefresh(view);
}
// Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
function triggerDOMRefresh(view){
if (view._isShown && view._isRendered && isInDOM(view)){
if (_.isFunction(view.triggerMethod)){
view.triggerMethod("dom:refresh");
}
}
}
function isInDOM(view) {
return documentElement.contains(view.el);
}
// Export public API
return function(view){
view.listenTo(view, "show", function(){
handleShow(view);
});
view.listenTo(view, "render", function(){
handleRender(view);
});
};
})(document.documentElement);
// Marionette.bindEntityEvents & unbindEntityEvents
// ---------------------------
//
// These methods are used to bind/unbind a backbone "entity" (collection/model)
// to methods on a target object.
//
// The first parameter, `target`, must have a `listenTo` method from the
// EventBinder object.
//
// The second parameter is the entity (Backbone.Model or Backbone.Collection)
// to bind the events from.
//
// The third parameter is a hash of { "event:name": "eventHandler" }
// configuration. Multiple handlers can be separated by a space. A
// function can be supplied instead of a string handler name.
(function(Marionette){
"use strict";
// Bind the event to handlers specified as a string of
// handler names on the target object
function bindFromStrings(target, entity, evt, methods){
var methodNames = methods.split(/\s+/);
_.each(methodNames,function(methodName) {
var method = target[methodName];
if(!method) {
throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
}
target.listenTo(entity, evt, method, target);
});
}
// Bind the event to a supplied callback function
function bindToFunction(target, entity, evt, method){
target.listenTo(entity, evt, method, target);
}
// Bind the event to handlers specified as a string of
// handler names on the target object
function unbindFromStrings(target, entity, evt, methods){
var methodNames = methods.split(/\s+/);
_.each(methodNames,function(methodName) {
var method = target[methodName];
target.stopListening(entity, evt, method, target);
});
}
// Bind the event to a supplied callback function
function unbindToFunction(target, entity, evt, method){
target.stopListening(entity, evt, method, target);
}
// generic looping function
function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
if (!entity || !bindings) { return; }
// allow the bindings to be a function
if (_.isFunction(bindings)){
bindings = bindings.call(target);
}
// iterate the bindings and bind them
_.each(bindings, function(methods, evt){
// allow for a function as the handler,
// or a list of event names as a string
if (_.isFunction(methods)){
functionCallback(target, entity, evt, methods);
} else {
stringCallback(target, entity, evt, methods);
}
});
}
// Export Public API
Marionette.bindEntityEvents = function(target, entity, bindings){
iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
};
Marionette.unbindEntityEvents = function(target, entity, bindings){
iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
};
})(Marionette);
// Callbacks
// ---------
// A simple way of managing a collection of callbacks
// and executing them at a later point in time, using jQuery's
// `Deferred` object.
Marionette.Callbacks = function(){
this._deferred = Marionette.$.Deferred();
this._callbacks = [];
};
_.extend(Marionette.Callbacks.prototype, {
// Add a callback to be executed. Callbacks added here are
// guaranteed to execute, even if they are added after the
// `run` method is called.
add: function(callback, contextOverride){
this._callbacks.push({cb: callback, ctx: contextOverride});
this._deferred.done(function(context, options){
if (contextOverride){ context = contextOverride; }
callback.call(context, options);
});
},
// Run all registered callbacks with the context specified.
// Additional callbacks can be added after this has been run
// and they will still be executed.
run: function(options, context){
this._deferred.resolve(context, options);
},
// Resets the list of callbacks to be run, allowing the same list
// to be run multiple times - whenever the `run` method is called.
reset: function(){
var callbacks = this._callbacks;
this._deferred = Marionette.$.Deferred();
this._callbacks = [];
_.each(callbacks, function(cb){
this.add(cb.cb, cb.ctx);
}, this);
}
});
// Marionette Controller
// ---------------------
//
// A multi-purpose object to use as a controller for
// modules and routers, and as a mediator for workflow
// and coordination of other objects, views, and more.
Marionette.Controller = function(options){
this.triggerMethod = Marionette.triggerMethod;
this.options = options || {};
if (_.isFunction(this.initialize)){
this.initialize(this.options);
}
};
Marionette.Controller.extend = Marionette.extend;
// Controller Methods
// --------------
// Ensure it can trigger events with Backbone.Events
_.extend(Marionette.Controller.prototype, Backbone.Events, {
close: function(){
this.stopListening();
this.triggerMethod("close");
this.unbind();
}
});
// 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 || {};
this.el = Marionette.getOption(this, "el");
if (!this.el){
var err = new Error("An 'el' must be specified for a region.");
err.name = "NoElError";
throw err;
}
if (this.initialize){
var args = Array.prototype.slice.apply(arguments);
this.initialize.apply(this, args);
}
};
// 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;
delete regionConfig.selector;
}
// get the type for the region
if (regionIsType){
RegionType = regionConfig;
}
if (!regionIsType && regionTypeIsUndefined) {
RegionType = defaultRegionType;
}
if (regionConfig.regionType) {
RegionType = regionConfig.regionType;
delete regionConfig.regionType;
}
if (regionIsString || regionIsType) {
regionConfig = {};
}
regionConfig.el = selector;
// build the region instance
var region = new RegionType(regionConfig);
// override the `getEl` function if we have a parentEl
// this must be overridden to ensure the selector is found
// on the first use of the region. if we try to assign the
// region's `el` to `parentEl.find(selector)` in the object
// literal to build the region, the element will not be
// guaranteed to be in the DOM already, and will cause problems
if (regionConfig.parentEl){
region.getEl = function(selector) {
var parentEl = regionConfig.parentEl;
if (_.isFunction(parentEl)){
parentEl = parentEl();
}
return parentEl.find(selector);
};
}
return region;
}
});
// 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();
var isViewClosed = view.isClosed || _.isUndefined(view.$el);
var isDifferentView = view !== this.currentView;
if (isDifferentView) {
this.close();
}
view.render();
if (isDifferentView || isViewClosed) {
this.open(view);
}
this.currentView = view;
Marionette.triggerMethod.call(this, "show", view);
Marionette.triggerMethod.call(view, "show");
},
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 Marionette.$(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.empty().append(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; }
// call 'close' or 'remove', depending on which is found
if (view.close) { view.close(); }
else if (view.remove) { view.remove(); }
Marionette.triggerMethod.call(this, "close", 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;
// Marionette.RegionManager
// ------------------------
//
// Manage one or more related `Marionette.Region` objects.
Marionette.RegionManager = (function(Marionette){
var RegionManager = Marionette.Controller.extend({
constructor: function(options){
this._regions = {};
Marionette.Controller.prototype.constructor.call(this, options);
},
// Add multiple regions using an object literal, where
// each key becomes the region name, and each value is
// the region definition.
addRegions: function(regionDefinitions, defaults){
var regions = {};
_.each(regionDefinitions, function(definition, name){
if (typeof definition === "string"){
definition = { selector: definition };
}
if (definition.selector){
definition = _.defaults({}, definition, defaults);
}
var region = this.addRegion(name, definition);
regions[name] = region;
}, this);
return regions;
},
// Add an individual region to the region manager,
// and return the region instance
addRegion: function(name, definition){
var region;
var isObject = _.isObject(definition);
var isString = _.isString(definition);
var hasSelector = !!definition.selector;
if (isString || (isObject && hasSelector)){
region = Marionette.Region.buildRegion(definition, Marionette.Region);
} else if (_.isFunction(definition)){
region = Marionette.Region.buildRegion(definition, Marionette.Region);
} else {
region = definition;
}
this._store(name, region);
this.triggerMethod("region:add", name, region);
return region;
},
// Get a region by name
get: function(name){
return this._regions[name];
},
// Remove a region by name
removeRegion: function(name){
var region = this._regions[name];
this._remove(name, region);
},
// Close all regions in the region manager, and
// remove them
removeRegions: function(){
_.each(this._regions, function(region, name){
this._remove(name, region);
}, this);
},
// Close all regions in the region manager, but
// leave them attached
closeRegions: function(){
_.each(this._regions, function(region, name){
region.close();
}, this);
},
// Close all regions and shut down the region
// manager entirely
close: function(){
this.removeRegions();
var args = Array.prototype.slice.call(arguments);
Marionette.Controller.prototype.close.apply(this, args);
},
// internal method to store regions
_store: function(name, region){
this._regions[name] = region;
this._setLength();
},
// internal method to remove a region
_remove: function(name, region){
region.close();
delete this._regions[name];
this._setLength();
this.triggerMethod("region:remove", name, region);
},
// set the number of regions current held
_setLength: function(){
this.length = _.size(this._regions);
}
});
// Borrowing this code from Backbone.Collection:
// http://backbonejs.org/docs/backbone.html#section-106
//
// Mix in methods from Underscore, for iteration, and other
// collection related features.
var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
'select', 'reject', 'every', 'all', 'some', 'any', 'include',
'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
'last', 'without', 'isEmpty', 'pluck'];
_.each(methods, function(method) {
RegionManager.prototype[method] = function() {
var regions = _.values(this._regions);
var args = [regions].concat(_.toArray(arguments));
return _[method].apply(_, args);
};
});
return RegionManager;
})(Marionette);
// Template Cache
// --------------
// Manage templates stored in `<script>` blocks,
// caching them for faster access.
Marionette.TemplateCache = function(templateId){
this.templateId = templateId;
};
// TemplateCache object-level methods. Manage the template
// caches from these method calls instead of creating
// your own TemplateCache instances
_.extend(Marionette.TemplateCache, {
templateCaches: {},
// Get the specified template by id. Either
// retrieves the cached version, or loads it
// from the DOM.
get: function(templateId){
var cachedTemplate = this.templateCaches[templateId];
if (!cachedTemplate){
cachedTemplate = new Marionette.TemplateCache(templateId);
this.templateCaches[templateId] = cachedTemplate;
}
return cachedTemplate.load();
},
// Clear templates from the cache. If no arguments
// are specified, clears all templates:
// `clear()`
//
// If arguments are specified, clears each of the
// specified templates from the cache:
// `clear("#t1", "#t2", "...")`
clear: function(){
var i;
var args = slice(arguments);
var length = args.length;
if (length > 0){
for(i=0; i<length; i++){
delete this.templateCaches[args[i]];
}
} else {
this.templateCaches = {};
}
}
});
// TemplateCache instance methods, allowing each
// template cache object to manage its own state
// and know whether or not it has been loaded
_.extend(Marionette.TemplateCache.prototype, {
// Internal method to load the template
load: function(){
// Guard clause to prevent loading this template more than once
if (this.compiledTemplate){
return this.compiledTemplate;
}
// Load the template and compile it
var template = this.loadTemplate(this.templateId);
this.compiledTemplate = this.compileTemplate(template);
return this.compiledTemplate;
},
// Load a template from the DOM, by default. Override
// this method to provide your own template retrieval
// For asynchronous loading with AMD/RequireJS, consider
// using a template-loader plugin as described here:
// https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
loadTemplate: function(templateId){
var template = Marionette.$(templateId).html();
if (!template || template.length === 0){
throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
}
return template;
},
// Pre-compile the template before caching it. Override
// this method if you do not need to pre-compile a template
// (JST / RequireJS for example) or if you want to change
// the template engine used (Handebars, etc).
compileTemplate: function(rawTemplate){
return _.template(rawTemplate);
}
});
// Renderer
// --------
// Render a template with data by passing in the template
// selector and the data to render.
Marionette.Renderer = {
// Render a template with data. The `template` parameter is
// passed to the `TemplateCache` object to retrieve the
// template function. Override this method to provide your own
// custom rendering and template handling for all of Marionette.
render: function(template, data){
if (!template) {
var error = new Error("Cannot render the template since it's false, null or undefined.");
error.name = "TemplateNotFoundError";
throw error;
}
var templateFunc;
if (typeof template === "function"){
templateFunc = template;
} else {
templateFunc = Marionette.TemplateCache.get(template);
}
return templateFunc(data);
}
};
// Marionette.View
// ---------------
// The core view type that other Marionette views extend from.
Marionette.View = Backbone.View.extend({
constructor: function(options){
_.bindAll(this, "render");
var args = Array.prototype.slice.apply(arguments);
// this exposes view options to the view initializer
// this is a backfill since backbone removed the assignment
// of this.options
// at some point however this may be removed
this.options = _.extend({}, _.result(this, 'options'), _.isFunction(options) ? options.call(this) : options);
// parses out the @ui DSL for events
this.events = this.normalizeUIKeys(_.result(this, 'events'));
Backbone.View.prototype.constructor.apply(this, args);
Marionette.MonitorDOMRefresh(this);
this.listenTo(this, "show", this.onShowCalled, this);
},
// import the "triggerMethod" to trigger events with corresponding
// methods if the method exists
triggerMethod: Marionette.triggerMethod,
// Imports the "normalizeMethods" to transform hashes of
// events=>function references/names to a hash of events=>function references
normalizeMethods: Marionette.normalizeMethods,
// 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(){
return Marionette.getOption(this, "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 = Marionette.getOption(this, "templateHelpers");
if (_.isFunction(templateHelpers)){
templateHelpers = templateHelpers.call(this);
}
return _.extend(target, templateHelpers);
},
// allows for the use of the @ui. syntax within
// a given key for triggers and events
// swaps the @ui with the associated selector
normalizeUIKeys: function(hash) {
if (typeof(hash) === "undefined") {
return;
}
_.each(_.keys(hash), function(v) {
var split = v.split("@ui.");
if (split.length === 2) {
hash[split[0]+this.ui[split[1]]] = hash[v];
delete hash[v];
}
}, this);
return hash;
},
// Configure `triggers` to forward DOM events to view
// events. `triggers: {"click .foo": "do:foo"}`
configureTriggers: function(){
if (!this.triggers) { return; }
var triggerEvents = {};
// Allow `triggers` to be configured as a function
var triggers = this.normalizeUIKeys(_.result(this, "triggers"));
// Configure the triggers, prevent default
// action and stop propagation of DOM events
_.each(triggers, function(value, key){
var hasOptions = _.isObject(value);
var eventName = hasOptions ? value.event : value;
// build the event handler function for the DOM event
triggerEvents[key] = function(e){
// stop the event in its tracks
if (e) {
var prevent = e.preventDefault;
var stop = e.stopPropagation;
var shouldPrevent = hasOptions ? value.preventDefault : prevent;
var shouldStop = hasOptions ? value.stopPropagation : stop;
if (shouldPrevent && prevent) { prevent.apply(e); }
if (shouldStop && stop) { stop.apply(e); }
}
// build the args for the event
var args = {
view: this,
model: this.model,
collection: this.collection
};
// trigger the event
this.triggerMethod(eventName, args);
};
}, this);
return triggerEvents;
},
// Overriding Backbone.View's delegateEvents to handle
// the `triggers`, `modelEvents`, and `collectionEvents` configuration
delegateEvents: function(events){
this._delegateDOMEvents(events);
Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
},
// internal method to delegate DOM events and triggers
_delegateDOMEvents: 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);
},
// Overriding Backbone.View's undelegateEvents to handle unbinding
// the `triggers`, `modelEvents`, and `collectionEvents` config
undelegateEvents: function(){
var args = Array.prototype.slice.call(arguments);
Backbone.View.prototype.undelegateEvents.apply(this, args);
Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
},
// 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; }
// allow the close to be stopped by returning `false`
// from the `onBeforeClose` method
var shouldClose = this.triggerMethod("before:close");
if (shouldClose === false){
return;
}
// mark as closed before doing the actual close, to
// prevent infinite loops within "close" event handlers
// that are trying to close other views
this.isClosed = true;
this.triggerMethod("close");
// unbind UI elements
this.unbindUIElements();
// remove the view from the DOM
this.remove();
},
// 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; }
// store the ui hash in _uiBindings so they can be reset later
// and so re-rendering the view will be able to find the bindings
if (!this._uiBindings){
this._uiBindings = this.ui;
}
// get the bindings result, as a function or otherwise
var bindings = _.result(this, "_uiBindings");
// empty the ui so we don't have anything to start with
this.ui = {};
// bind each of the selectors
_.each(_.keys(bindings), function(key) {
var selector = bindings[key];
this.ui[key] = this.$(selector);
}, this);
},
// This method unbinds the elements specified in the "ui" hash
unbindUIElements: function(){
if (!this.ui || !this._uiBindings){ return; }
// delete all of the existing ui bindings
_.each(this.ui, function($el, name){
delete this.ui[name];
}, this);
// reset the ui element to the original bindings configuration
this.ui = this._uiBindings;
delete this._uiBindings;
}
});
// Item View