PageRenderTime 64ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/bower_components/backbone.marionette/lib/core/amd/backbone.marionette.js

https://github.com/robertd/benm
JavaScript | 2062 lines | 1093 code | 419 blank | 550 comment | 147 complexity | 03c18b3edde7bd42e5bd789fa2f826bb MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. // MarionetteJS (Backbone.Marionette)
  2. // ----------------------------------
  3. // v1.4.1
  4. //
  5. // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
  6. // Distributed under MIT license
  7. //
  8. // http://marionettejs.com
  9. /*!
  10. * Includes BabySitter
  11. * https://github.com/marionettejs/backbone.babysitter/
  12. *
  13. * Includes Wreqr
  14. * https://github.com/marionettejs/backbone.wreqr/
  15. */
  16. (function (root, factory) {
  17. if (typeof exports === 'object') {
  18. var underscore = require('underscore');
  19. var backbone = require('backbone');
  20. var wreqr = require('backbone.wreqr');
  21. var babysitter = require('backbone.babysitter');
  22. module.exports = factory(underscore, backbone, wreqr, babysitter);
  23. } else if (typeof define === 'function' && define.amd) {
  24. define(['underscore', 'backbone', 'backbone.wreqr', 'backbone.babysitter'], factory);
  25. }
  26. }(this, function (_, Backbone) {
  27. var Marionette = (function(global, Backbone, _){
  28. "use strict";
  29. // Define and export the Marionette namespace
  30. var Marionette = {};
  31. Backbone.Marionette = Marionette;
  32. // Get the DOM manipulator for later use
  33. Marionette.$ = Backbone.$;
  34. // Helpers
  35. // -------
  36. // For slicing `arguments` in functions
  37. var protoSlice = Array.prototype.slice;
  38. function slice(args) {
  39. return protoSlice.call(args);
  40. }
  41. function throwError(message, name) {
  42. var error = new Error(message);
  43. error.name = name || 'Error';
  44. throw error;
  45. }
  46. // Marionette.extend
  47. // -----------------
  48. // Borrow the Backbone `extend` method so we can use it as needed
  49. Marionette.extend = Backbone.Model.extend;
  50. // Marionette.getOption
  51. // --------------------
  52. // Retrieve an object, function or other value from a target
  53. // object or its `options`, with `options` taking precedence.
  54. Marionette.getOption = function(target, optionName){
  55. if (!target || !optionName){ return; }
  56. var value;
  57. if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
  58. value = target.options[optionName];
  59. } else {
  60. value = target[optionName];
  61. }
  62. return value;
  63. };
  64. // Trigger an event and/or a corresponding method name. Examples:
  65. //
  66. // `this.triggerMethod("foo")` will trigger the "foo" event and
  67. // call the "onFoo" method.
  68. //
  69. // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
  70. // call the "onFooBar" method.
  71. Marionette.triggerMethod = (function(){
  72. // split the event name on the :
  73. var splitter = /(^|:)(\w)/gi;
  74. // take the event section ("section1:section2:section3")
  75. // and turn it in to uppercase name
  76. function getEventName(match, prefix, eventName) {
  77. return eventName.toUpperCase();
  78. }
  79. // actual triggerMethod name
  80. var triggerMethod = function(event) {
  81. // get the method name from the event name
  82. var methodName = 'on' + event.replace(splitter, getEventName);
  83. var method = this[methodName];
  84. // trigger the event, if a trigger method exists
  85. if(_.isFunction(this.trigger)) {
  86. this.trigger.apply(this, arguments);
  87. }
  88. // call the onMethodName if it exists
  89. if (_.isFunction(method)) {
  90. // pass all arguments, except the event name
  91. return method.apply(this, _.tail(arguments));
  92. }
  93. };
  94. return triggerMethod;
  95. })();
  96. // DOMRefresh
  97. // ----------
  98. //
  99. // Monitor a view's state, and after it has been rendered and shown
  100. // in the DOM, trigger a "dom:refresh" event every time it is
  101. // re-rendered.
  102. Marionette.MonitorDOMRefresh = (function(){
  103. // track when the view has been shown in the DOM,
  104. // using a Marionette.Region (or by other means of triggering "show")
  105. function handleShow(view){
  106. view._isShown = true;
  107. triggerDOMRefresh(view);
  108. }
  109. // track when the view has been rendered
  110. function handleRender(view){
  111. view._isRendered = true;
  112. triggerDOMRefresh(view);
  113. }
  114. // Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
  115. function triggerDOMRefresh(view){
  116. if (view._isShown && view._isRendered){
  117. if (_.isFunction(view.triggerMethod)){
  118. view.triggerMethod("dom:refresh");
  119. }
  120. }
  121. }
  122. // Export public API
  123. return function(view){
  124. view.listenTo(view, "show", function(){
  125. handleShow(view);
  126. });
  127. view.listenTo(view, "render", function(){
  128. handleRender(view);
  129. });
  130. };
  131. })();
  132. // Marionette.bindEntityEvents & unbindEntityEvents
  133. // ---------------------------
  134. //
  135. // These methods are used to bind/unbind a backbone "entity" (collection/model)
  136. // to methods on a target object.
  137. //
  138. // The first parameter, `target`, must have a `listenTo` method from the
  139. // EventBinder object.
  140. //
  141. // The second parameter is the entity (Backbone.Model or Backbone.Collection)
  142. // to bind the events from.
  143. //
  144. // The third parameter is a hash of { "event:name": "eventHandler" }
  145. // configuration. Multiple handlers can be separated by a space. A
  146. // function can be supplied instead of a string handler name.
  147. (function(Marionette){
  148. "use strict";
  149. // Bind the event to handlers specified as a string of
  150. // handler names on the target object
  151. function bindFromStrings(target, entity, evt, methods){
  152. var methodNames = methods.split(/\s+/);
  153. _.each(methodNames,function(methodName) {
  154. var method = target[methodName];
  155. if(!method) {
  156. throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
  157. }
  158. target.listenTo(entity, evt, method, target);
  159. });
  160. }
  161. // Bind the event to a supplied callback function
  162. function bindToFunction(target, entity, evt, method){
  163. target.listenTo(entity, evt, method, target);
  164. }
  165. // Bind the event to handlers specified as a string of
  166. // handler names on the target object
  167. function unbindFromStrings(target, entity, evt, methods){
  168. var methodNames = methods.split(/\s+/);
  169. _.each(methodNames,function(methodName) {
  170. var method = target[methodName];
  171. target.stopListening(entity, evt, method, target);
  172. });
  173. }
  174. // Bind the event to a supplied callback function
  175. function unbindToFunction(target, entity, evt, method){
  176. target.stopListening(entity, evt, method, target);
  177. }
  178. // generic looping function
  179. function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
  180. if (!entity || !bindings) { return; }
  181. // allow the bindings to be a function
  182. if (_.isFunction(bindings)){
  183. bindings = bindings.call(target);
  184. }
  185. // iterate the bindings and bind them
  186. _.each(bindings, function(methods, evt){
  187. // allow for a function as the handler,
  188. // or a list of event names as a string
  189. if (_.isFunction(methods)){
  190. functionCallback(target, entity, evt, methods);
  191. } else {
  192. stringCallback(target, entity, evt, methods);
  193. }
  194. });
  195. }
  196. // Export Public API
  197. Marionette.bindEntityEvents = function(target, entity, bindings){
  198. iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
  199. };
  200. Marionette.unbindEntityEvents = function(target, entity, bindings){
  201. iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
  202. };
  203. })(Marionette);
  204. // Callbacks
  205. // ---------
  206. // A simple way of managing a collection of callbacks
  207. // and executing them at a later point in time, using jQuery's
  208. // `Deferred` object.
  209. Marionette.Callbacks = function(){
  210. this._deferred = Marionette.$.Deferred();
  211. this._callbacks = [];
  212. };
  213. _.extend(Marionette.Callbacks.prototype, {
  214. // Add a callback to be executed. Callbacks added here are
  215. // guaranteed to execute, even if they are added after the
  216. // `run` method is called.
  217. add: function(callback, contextOverride){
  218. this._callbacks.push({cb: callback, ctx: contextOverride});
  219. this._deferred.done(function(context, options){
  220. if (contextOverride){ context = contextOverride; }
  221. callback.call(context, options);
  222. });
  223. },
  224. // Run all registered callbacks with the context specified.
  225. // Additional callbacks can be added after this has been run
  226. // and they will still be executed.
  227. run: function(options, context){
  228. this._deferred.resolve(context, options);
  229. },
  230. // Resets the list of callbacks to be run, allowing the same list
  231. // to be run multiple times - whenever the `run` method is called.
  232. reset: function(){
  233. var callbacks = this._callbacks;
  234. this._deferred = Marionette.$.Deferred();
  235. this._callbacks = [];
  236. _.each(callbacks, function(cb){
  237. this.add(cb.cb, cb.ctx);
  238. }, this);
  239. }
  240. });
  241. // Marionette Controller
  242. // ---------------------
  243. //
  244. // A multi-purpose object to use as a controller for
  245. // modules and routers, and as a mediator for workflow
  246. // and coordination of other objects, views, and more.
  247. Marionette.Controller = function(options){
  248. this.triggerMethod = Marionette.triggerMethod;
  249. this.options = options || {};
  250. if (_.isFunction(this.initialize)){
  251. this.initialize(this.options);
  252. }
  253. };
  254. Marionette.Controller.extend = Marionette.extend;
  255. // Controller Methods
  256. // --------------
  257. // Ensure it can trigger events with Backbone.Events
  258. _.extend(Marionette.Controller.prototype, Backbone.Events, {
  259. close: function(){
  260. this.stopListening();
  261. this.triggerMethod("close");
  262. this.unbind();
  263. }
  264. });
  265. // Region
  266. // ------
  267. //
  268. // Manage the visual regions of your composite application. See
  269. // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
  270. Marionette.Region = function(options){
  271. this.options = options || {};
  272. this.el = Marionette.getOption(this, "el");
  273. if (!this.el){
  274. var err = new Error("An 'el' must be specified for a region.");
  275. err.name = "NoElError";
  276. throw err;
  277. }
  278. if (this.initialize){
  279. var args = Array.prototype.slice.apply(arguments);
  280. this.initialize.apply(this, args);
  281. }
  282. };
  283. // Region Type methods
  284. // -------------------
  285. _.extend(Marionette.Region, {
  286. // Build an instance of a region by passing in a configuration object
  287. // and a default region type to use if none is specified in the config.
  288. //
  289. // The config object should either be a string as a jQuery DOM selector,
  290. // a Region type directly, or an object literal that specifies both
  291. // a selector and regionType:
  292. //
  293. // ```js
  294. // {
  295. // selector: "#foo",
  296. // regionType: MyCustomRegion
  297. // }
  298. // ```
  299. //
  300. buildRegion: function(regionConfig, defaultRegionType){
  301. var regionIsString = (typeof regionConfig === "string");
  302. var regionSelectorIsString = (typeof regionConfig.selector === "string");
  303. var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
  304. var regionIsType = (typeof regionConfig === "function");
  305. if (!regionIsType && !regionIsString && !regionSelectorIsString) {
  306. throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
  307. }
  308. var selector, RegionType;
  309. // get the selector for the region
  310. if (regionIsString) {
  311. selector = regionConfig;
  312. }
  313. if (regionConfig.selector) {
  314. selector = regionConfig.selector;
  315. }
  316. // get the type for the region
  317. if (regionIsType){
  318. RegionType = regionConfig;
  319. }
  320. if (!regionIsType && regionTypeIsUndefined) {
  321. RegionType = defaultRegionType;
  322. }
  323. if (regionConfig.regionType) {
  324. RegionType = regionConfig.regionType;
  325. }
  326. // build the region instance
  327. var region = new RegionType({
  328. el: selector
  329. });
  330. // override the `getEl` function if we have a parentEl
  331. // this must be overridden to ensure the selector is found
  332. // on the first use of the region. if we try to assign the
  333. // region's `el` to `parentEl.find(selector)` in the object
  334. // literal to build the region, the element will not be
  335. // guaranteed to be in the DOM already, and will cause problems
  336. if (regionConfig.parentEl){
  337. region.getEl = function(selector) {
  338. var parentEl = regionConfig.parentEl;
  339. if (_.isFunction(parentEl)){
  340. parentEl = parentEl();
  341. }
  342. return parentEl.find(selector);
  343. };
  344. }
  345. return region;
  346. }
  347. });
  348. // Region Instance Methods
  349. // -----------------------
  350. _.extend(Marionette.Region.prototype, Backbone.Events, {
  351. // Displays a backbone view instance inside of the region.
  352. // Handles calling the `render` method for you. Reads content
  353. // directly from the `el` attribute. Also calls an optional
  354. // `onShow` and `close` method on your view, just after showing
  355. // or just before closing the view, respectively.
  356. show: function(view){
  357. this.ensureEl();
  358. var isViewClosed = view.isClosed || _.isUndefined(view.$el);
  359. var isDifferentView = view !== this.currentView;
  360. if (isDifferentView) {
  361. this.close();
  362. }
  363. view.render();
  364. if (isDifferentView || isViewClosed) {
  365. this.open(view);
  366. }
  367. this.currentView = view;
  368. Marionette.triggerMethod.call(this, "show", view);
  369. Marionette.triggerMethod.call(view, "show");
  370. },
  371. ensureEl: function(){
  372. if (!this.$el || this.$el.length === 0){
  373. this.$el = this.getEl(this.el);
  374. }
  375. },
  376. // Override this method to change how the region finds the
  377. // DOM element that it manages. Return a jQuery selector object.
  378. getEl: function(selector){
  379. return Marionette.$(selector);
  380. },
  381. // Override this method to change how the new view is
  382. // appended to the `$el` that the region is managing
  383. open: function(view){
  384. this.$el.empty().append(view.el);
  385. },
  386. // Close the current view, if there is one. If there is no
  387. // current view, it does nothing and returns immediately.
  388. close: function(){
  389. var view = this.currentView;
  390. if (!view || view.isClosed){ return; }
  391. // call 'close' or 'remove', depending on which is found
  392. if (view.close) { view.close(); }
  393. else if (view.remove) { view.remove(); }
  394. Marionette.triggerMethod.call(this, "close");
  395. delete this.currentView;
  396. },
  397. // Attach an existing view to the region. This
  398. // will not call `render` or `onShow` for the new view,
  399. // and will not replace the current HTML for the `el`
  400. // of the region.
  401. attachView: function(view){
  402. this.currentView = view;
  403. },
  404. // Reset the region by closing any existing view and
  405. // clearing out the cached `$el`. The next time a view
  406. // is shown via this region, the region will re-query the
  407. // DOM for the region's `el`.
  408. reset: function(){
  409. this.close();
  410. delete this.$el;
  411. }
  412. });
  413. // Copy the `extend` function used by Backbone's classes
  414. Marionette.Region.extend = Marionette.extend;
  415. // Marionette.RegionManager
  416. // ------------------------
  417. //
  418. // Manage one or more related `Marionette.Region` objects.
  419. Marionette.RegionManager = (function(Marionette){
  420. var RegionManager = Marionette.Controller.extend({
  421. constructor: function(options){
  422. this._regions = {};
  423. Marionette.Controller.prototype.constructor.call(this, options);
  424. },
  425. // Add multiple regions using an object literal, where
  426. // each key becomes the region name, and each value is
  427. // the region definition.
  428. addRegions: function(regionDefinitions, defaults){
  429. var regions = {};
  430. _.each(regionDefinitions, function(definition, name){
  431. if (typeof definition === "string"){
  432. definition = { selector: definition };
  433. }
  434. if (definition.selector){
  435. definition = _.defaults({}, definition, defaults);
  436. }
  437. var region = this.addRegion(name, definition);
  438. regions[name] = region;
  439. }, this);
  440. return regions;
  441. },
  442. // Add an individual region to the region manager,
  443. // and return the region instance
  444. addRegion: function(name, definition){
  445. var region;
  446. var isObject = _.isObject(definition);
  447. var isString = _.isString(definition);
  448. var hasSelector = !!definition.selector;
  449. if (isString || (isObject && hasSelector)){
  450. region = Marionette.Region.buildRegion(definition, Marionette.Region);
  451. } else if (_.isFunction(definition)){
  452. region = Marionette.Region.buildRegion(definition, Marionette.Region);
  453. } else {
  454. region = definition;
  455. }
  456. this._store(name, region);
  457. this.triggerMethod("region:add", name, region);
  458. return region;
  459. },
  460. // Get a region by name
  461. get: function(name){
  462. return this._regions[name];
  463. },
  464. // Remove a region by name
  465. removeRegion: function(name){
  466. var region = this._regions[name];
  467. this._remove(name, region);
  468. },
  469. // Close all regions in the region manager, and
  470. // remove them
  471. removeRegions: function(){
  472. _.each(this._regions, function(region, name){
  473. this._remove(name, region);
  474. }, this);
  475. },
  476. // Close all regions in the region manager, but
  477. // leave them attached
  478. closeRegions: function(){
  479. _.each(this._regions, function(region, name){
  480. region.close();
  481. }, this);
  482. },
  483. // Close all regions and shut down the region
  484. // manager entirely
  485. close: function(){
  486. this.removeRegions();
  487. var args = Array.prototype.slice.call(arguments);
  488. Marionette.Controller.prototype.close.apply(this, args);
  489. },
  490. // internal method to store regions
  491. _store: function(name, region){
  492. this._regions[name] = region;
  493. this._setLength();
  494. },
  495. // internal method to remove a region
  496. _remove: function(name, region){
  497. region.close();
  498. delete this._regions[name];
  499. this._setLength();
  500. this.triggerMethod("region:remove", name, region);
  501. },
  502. // set the number of regions current held
  503. _setLength: function(){
  504. this.length = _.size(this._regions);
  505. }
  506. });
  507. // Borrowing this code from Backbone.Collection:
  508. // http://backbonejs.org/docs/backbone.html#section-106
  509. //
  510. // Mix in methods from Underscore, for iteration, and other
  511. // collection related features.
  512. var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
  513. 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
  514. 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
  515. 'last', 'without', 'isEmpty', 'pluck'];
  516. _.each(methods, function(method) {
  517. RegionManager.prototype[method] = function() {
  518. var regions = _.values(this._regions);
  519. var args = [regions].concat(_.toArray(arguments));
  520. return _[method].apply(_, args);
  521. };
  522. });
  523. return RegionManager;
  524. })(Marionette);
  525. // Template Cache
  526. // --------------
  527. // Manage templates stored in `<script>` blocks,
  528. // caching them for faster access.
  529. Marionette.TemplateCache = function(templateId){
  530. this.templateId = templateId;
  531. };
  532. // TemplateCache object-level methods. Manage the template
  533. // caches from these method calls instead of creating
  534. // your own TemplateCache instances
  535. _.extend(Marionette.TemplateCache, {
  536. templateCaches: {},
  537. // Get the specified template by id. Either
  538. // retrieves the cached version, or loads it
  539. // from the DOM.
  540. get: function(templateId){
  541. var cachedTemplate = this.templateCaches[templateId];
  542. if (!cachedTemplate){
  543. cachedTemplate = new Marionette.TemplateCache(templateId);
  544. this.templateCaches[templateId] = cachedTemplate;
  545. }
  546. return cachedTemplate.load();
  547. },
  548. // Clear templates from the cache. If no arguments
  549. // are specified, clears all templates:
  550. // `clear()`
  551. //
  552. // If arguments are specified, clears each of the
  553. // specified templates from the cache:
  554. // `clear("#t1", "#t2", "...")`
  555. clear: function(){
  556. var i;
  557. var args = slice(arguments);
  558. var length = args.length;
  559. if (length > 0){
  560. for(i=0; i<length; i++){
  561. delete this.templateCaches[args[i]];
  562. }
  563. } else {
  564. this.templateCaches = {};
  565. }
  566. }
  567. });
  568. // TemplateCache instance methods, allowing each
  569. // template cache object to manage its own state
  570. // and know whether or not it has been loaded
  571. _.extend(Marionette.TemplateCache.prototype, {
  572. // Internal method to load the template
  573. load: function(){
  574. // Guard clause to prevent loading this template more than once
  575. if (this.compiledTemplate){
  576. return this.compiledTemplate;
  577. }
  578. // Load the template and compile it
  579. var template = this.loadTemplate(this.templateId);
  580. this.compiledTemplate = this.compileTemplate(template);
  581. return this.compiledTemplate;
  582. },
  583. // Load a template from the DOM, by default. Override
  584. // this method to provide your own template retrieval
  585. // For asynchronous loading with AMD/RequireJS, consider
  586. // using a template-loader plugin as described here:
  587. // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
  588. loadTemplate: function(templateId){
  589. var template = Marionette.$(templateId).html();
  590. if (!template || template.length === 0){
  591. throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
  592. }
  593. return template;
  594. },
  595. // Pre-compile the template before caching it. Override
  596. // this method if you do not need to pre-compile a template
  597. // (JST / RequireJS for example) or if you want to change
  598. // the template engine used (Handebars, etc).
  599. compileTemplate: function(rawTemplate){
  600. return _.template(rawTemplate);
  601. }
  602. });
  603. // Renderer
  604. // --------
  605. // Render a template with data by passing in the template
  606. // selector and the data to render.
  607. Marionette.Renderer = {
  608. // Render a template with data. The `template` parameter is
  609. // passed to the `TemplateCache` object to retrieve the
  610. // template function. Override this method to provide your own
  611. // custom rendering and template handling for all of Marionette.
  612. render: function(template, data){
  613. if (!template) {
  614. var error = new Error("Cannot render the template since it's false, null or undefined.");
  615. error.name = "TemplateNotFoundError";
  616. throw error;
  617. }
  618. var templateFunc;
  619. if (typeof template === "function"){
  620. templateFunc = template;
  621. } else {
  622. templateFunc = Marionette.TemplateCache.get(template);
  623. }
  624. return templateFunc(data);
  625. }
  626. };
  627. // Marionette.View
  628. // ---------------
  629. // The core view type that other Marionette views extend from.
  630. Marionette.View = Backbone.View.extend({
  631. constructor: function(options){
  632. _.bindAll(this, "render");
  633. var args = Array.prototype.slice.apply(arguments);
  634. // this exposes view options to the view initializer
  635. // this is a backfill since backbone removed the assignment
  636. // of this.options
  637. // at some point however this may be removed
  638. this.options = _.extend({}, this.options, options);
  639. // parses out the @ui DSL for events
  640. this.events = this.normalizeUIKeys(_.result(this, 'events'));
  641. Backbone.View.prototype.constructor.apply(this, args);
  642. Marionette.MonitorDOMRefresh(this);
  643. this.listenTo(this, "show", this.onShowCalled, this);
  644. },
  645. // import the "triggerMethod" to trigger events with corresponding
  646. // methods if the method exists
  647. triggerMethod: Marionette.triggerMethod,
  648. // Get the template for this view
  649. // instance. You can set a `template` attribute in the view
  650. // definition or pass a `template: "whatever"` parameter in
  651. // to the constructor options.
  652. getTemplate: function(){
  653. return Marionette.getOption(this, "template");
  654. },
  655. // Mix in template helper methods. Looks for a
  656. // `templateHelpers` attribute, which can either be an
  657. // object literal, or a function that returns an object
  658. // literal. All methods and attributes from this object
  659. // are copies to the object passed in.
  660. mixinTemplateHelpers: function(target){
  661. target = target || {};
  662. var templateHelpers = Marionette.getOption(this, "templateHelpers");
  663. if (_.isFunction(templateHelpers)){
  664. templateHelpers = templateHelpers.call(this);
  665. }
  666. return _.extend(target, templateHelpers);
  667. },
  668. // allows for the use of the @ui. syntax within
  669. // a given key for triggers and events
  670. // swaps the @ui with the associated selector
  671. normalizeUIKeys: function(hash) {
  672. if (typeof(hash) === "undefined") {
  673. return;
  674. }
  675. _.each(_.keys(hash), function(v) {
  676. var split = v.split("@ui.");
  677. if (split.length === 2) {
  678. hash[split[0]+this.ui[split[1]]] = hash[v];
  679. delete hash[v];
  680. }
  681. }, this);
  682. return hash;
  683. },
  684. // Configure `triggers` to forward DOM events to view
  685. // events. `triggers: {"click .foo": "do:foo"}`
  686. configureTriggers: function(){
  687. if (!this.triggers) { return; }
  688. var triggerEvents = {};
  689. // Allow `triggers` to be configured as a function
  690. var triggers = this.normalizeUIKeys(_.result(this, "triggers"));
  691. // Configure the triggers, prevent default
  692. // action and stop propagation of DOM events
  693. _.each(triggers, function(value, key){
  694. var hasOptions = _.isObject(value);
  695. var eventName = hasOptions ? value.event : value;
  696. // build the event handler function for the DOM event
  697. triggerEvents[key] = function(e){
  698. // stop the event in its tracks
  699. if (e) {
  700. var prevent = e.preventDefault;
  701. var stop = e.stopPropagation;
  702. var shouldPrevent = hasOptions ? value.preventDefault : prevent;
  703. var shouldStop = hasOptions ? value.stopPropagation : stop;
  704. if (shouldPrevent && prevent) { prevent.apply(e); }
  705. if (shouldStop && stop) { stop.apply(e); }
  706. }
  707. // build the args for the event
  708. var args = {
  709. view: this,
  710. model: this.model,
  711. collection: this.collection
  712. };
  713. // trigger the event
  714. this.triggerMethod(eventName, args);
  715. };
  716. }, this);
  717. return triggerEvents;
  718. },
  719. // Overriding Backbone.View's delegateEvents to handle
  720. // the `triggers`, `modelEvents`, and `collectionEvents` configuration
  721. delegateEvents: function(events){
  722. this._delegateDOMEvents(events);
  723. Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
  724. Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
  725. },
  726. // internal method to delegate DOM events and triggers
  727. _delegateDOMEvents: function(events){
  728. events = events || this.events;
  729. if (_.isFunction(events)){ events = events.call(this); }
  730. var combinedEvents = {};
  731. var triggers = this.configureTriggers();
  732. _.extend(combinedEvents, events, triggers);
  733. Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
  734. },
  735. // Overriding Backbone.View's undelegateEvents to handle unbinding
  736. // the `triggers`, `modelEvents`, and `collectionEvents` config
  737. undelegateEvents: function(){
  738. var args = Array.prototype.slice.call(arguments);
  739. Backbone.View.prototype.undelegateEvents.apply(this, args);
  740. Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
  741. Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
  742. },
  743. // Internal method, handles the `show` event.
  744. onShowCalled: function(){},
  745. // Default `close` implementation, for removing a view from the
  746. // DOM and unbinding it. Regions will call this method
  747. // for you. You can specify an `onClose` method in your view to
  748. // add custom code that is called after the view is closed.
  749. close: function(){
  750. if (this.isClosed) { return; }
  751. // allow the close to be stopped by returning `false`
  752. // from the `onBeforeClose` method
  753. var shouldClose = this.triggerMethod("before:close");
  754. if (shouldClose === false){
  755. return;
  756. }
  757. // mark as closed before doing the actual close, to
  758. // prevent infinite loops within "close" event handlers
  759. // that are trying to close other views
  760. this.isClosed = true;
  761. this.triggerMethod("close");
  762. // unbind UI elements
  763. this.unbindUIElements();
  764. // remove the view from the DOM
  765. this.remove();
  766. },
  767. // This method binds the elements specified in the "ui" hash inside the view's code with
  768. // the associated jQuery selectors.
  769. bindUIElements: function(){
  770. if (!this.ui) { return; }
  771. // store the ui hash in _uiBindings so they can be reset later
  772. // and so re-rendering the view will be able to find the bindings
  773. if (!this._uiBindings){
  774. this._uiBindings = this.ui;
  775. }
  776. // get the bindings result, as a function or otherwise
  777. var bindings = _.result(this, "_uiBindings");
  778. // empty the ui so we don't have anything to start with
  779. this.ui = {};
  780. // bind each of the selectors
  781. _.each(_.keys(bindings), function(key) {
  782. var selector = bindings[key];
  783. this.ui[key] = this.$(selector);
  784. }, this);
  785. },
  786. // This method unbinds the elements specified in the "ui" hash
  787. unbindUIElements: function(){
  788. if (!this.ui || !this._uiBindings){ return; }
  789. // delete all of the existing ui bindings
  790. _.each(this.ui, function($el, name){
  791. delete this.ui[name];
  792. }, this);
  793. // reset the ui element to the original bindings configuration
  794. this.ui = this._uiBindings;
  795. delete this._uiBindings;
  796. }
  797. });
  798. // Item View
  799. // ---------
  800. // A single item view implementation that contains code for rendering
  801. // with underscore.js templates, serializing the view's model or collection,
  802. // and calling several methods on extended views, such as `onRender`.
  803. Marionette.ItemView = Marionette.View.extend({
  804. // Setting up the inheritance chain which allows changes to
  805. // Marionette.View.prototype.constructor which allows overriding
  806. constructor: function(){
  807. Marionette.View.prototype.constructor.apply(this, slice(arguments));
  808. },
  809. // Serialize the model or collection for the view. If a model is
  810. // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
  811. // is also called, but is used to populate an `items` array in the
  812. // resulting data. If both are found, defaults to the model.
  813. // You can override the `serializeData` method in your own view
  814. // definition, to provide custom serialization for your view's data.
  815. serializeData: function(){
  816. var data = {};
  817. if (this.model) {
  818. data = this.model.toJSON();
  819. }
  820. else if (this.collection) {
  821. data = { items: this.collection.toJSON() };
  822. }
  823. return data;
  824. },
  825. // Render the view, defaulting to underscore.js templates.
  826. // You can override this in your view definition to provide
  827. // a very specific rendering for your view. In general, though,
  828. // you should override the `Marionette.Renderer` object to
  829. // change how Marionette renders views.
  830. render: function(){
  831. this.isClosed = false;
  832. this.triggerMethod("before:render", this);
  833. this.triggerMethod("item:before:render", this);
  834. var data = this.serializeData();
  835. data = this.mixinTemplateHelpers(data);
  836. var template = this.getTemplate();
  837. var html = Marionette.Renderer.render(template, data);
  838. this.$el.html(html);
  839. this.bindUIElements();
  840. this.triggerMethod("render", this);
  841. this.triggerMethod("item:rendered", this);
  842. return this;
  843. },
  844. // Override the default close event to add a few
  845. // more events that are triggered.
  846. close: function(){
  847. if (this.isClosed){ return; }
  848. this.triggerMethod('item:before:close');
  849. Marionette.View.prototype.close.apply(this, slice(arguments));
  850. this.triggerMethod('item:closed');
  851. }
  852. });
  853. // Collection View
  854. // ---------------
  855. // A view that iterates over a Backbone.Collection
  856. // and renders an individual ItemView for each model.
  857. Marionette.CollectionView = Marionette.View.extend({
  858. // used as the prefix for item view events
  859. // that are forwarded through the collectionview
  860. itemViewEventPrefix: "itemview",
  861. // constructor
  862. constructor: function(options){
  863. this._initChildViewStorage();
  864. Marionette.View.prototype.constructor.apply(this, slice(arguments));
  865. this._initialEvents();
  866. this.initRenderBuffer();
  867. },
  868. // Instead of inserting elements one by one into the page,
  869. // it's much more performant to insert elements into a document
  870. // fragment and then insert that document fragment into the page
  871. initRenderBuffer: function() {
  872. this.elBuffer = document.createDocumentFragment();
  873. },
  874. startBuffering: function() {
  875. this.initRenderBuffer();
  876. this.isBuffering = true;
  877. },
  878. endBuffering: function() {
  879. this.appendBuffer(this, this.elBuffer);
  880. this.initRenderBuffer();
  881. this.isBuffering = false;
  882. },
  883. // Configured the initial events that the collection view
  884. // binds to. Override this method to prevent the initial
  885. // events, or to add your own initial events.
  886. _initialEvents: function(){
  887. if (this.collection){
  888. this.listenTo(this.collection, "add", this.addChildView, this);
  889. this.listenTo(this.collection, "remove", this.removeItemView, this);
  890. this.listenTo(this.collection, "reset", this.render, this);
  891. }
  892. },
  893. // Handle a child item added to the collection
  894. addChildView: function(item, collection, options){
  895. this.closeEmptyView();
  896. var ItemView = this.getItemView(item);
  897. var index = this.collection.indexOf(item);
  898. this.addItemView(item, ItemView, index);
  899. },
  900. // Override from `Marionette.View` to guarantee the `onShow` method
  901. // of child views is called.
  902. onShowCalled: function(){
  903. this.children.each(function(child){
  904. Marionette.triggerMethod.call(child, "show");
  905. });
  906. },
  907. // Internal method to trigger the before render callbacks
  908. // and events
  909. triggerBeforeRender: function(){
  910. this.triggerMethod("before:render", this);
  911. this.triggerMethod("collection:before:render", this);
  912. },
  913. // Internal method to trigger the rendered callbacks and
  914. // events
  915. triggerRendered: function(){
  916. this.triggerMethod("render", this);
  917. this.triggerMethod("collection:rendered", this);
  918. },
  919. // Render the collection of items. Override this method to
  920. // provide your own implementation of a render function for
  921. // the collection view.
  922. render: function(){
  923. this.isClosed = false;
  924. this.triggerBeforeRender();
  925. this._renderChildren();
  926. this.triggerRendered();
  927. return this;
  928. },
  929. // Internal method. Separated so that CompositeView can have
  930. // more control over events being triggered, around the rendering
  931. // process
  932. _renderChildren: function(){
  933. this.startBuffering();
  934. this.closeEmptyView();
  935. this.closeChildren();
  936. if (this.collection && this.collection.length > 0) {
  937. this.showCollection();
  938. } else {
  939. this.showEmptyView();
  940. }
  941. this.endBuffering();
  942. },
  943. // Internal method to loop through each item in the
  944. // collection view and show it
  945. showCollection: function(){
  946. var ItemView;
  947. this.collection.each(function(item, index){
  948. ItemView = this.getItemView(item);
  949. this.addItemView(item, ItemView, index);
  950. }, this);
  951. },
  952. // Internal method to show an empty view in place of
  953. // a collection of item views, when the collection is
  954. // empty
  955. showEmptyView: function(){
  956. var EmptyView = this.getEmptyView();
  957. if (EmptyView && !this._showingEmptyView){
  958. this._showingEmptyView = true;
  959. var model = new Backbone.Model();
  960. this.addItemView(model, EmptyView, 0);
  961. }
  962. },
  963. // Internal method to close an existing emptyView instance
  964. // if one exists. Called when a collection view has been
  965. // rendered empty, and then an item is added to the collection.
  966. closeEmptyView: function(){
  967. if (this._showingEmptyView){
  968. this.closeChildren();
  969. delete this._showingEmptyView;
  970. }
  971. },
  972. // Retrieve the empty view type
  973. getEmptyView: function(){
  974. return Marionette.getOption(this, "emptyView");
  975. },
  976. // Retrieve the itemView type, either from `this.options.itemView`
  977. // or from the `itemView` in the object definition. The "options"
  978. // takes precedence.
  979. getItemView: function(item){
  980. var itemView = Marionette.getOption(this, "itemView");
  981. if (!itemView){
  982. throwError("An `itemView` must be specified", "NoItemViewError");
  983. }
  984. return itemView;
  985. },
  986. // Render the child item's view and add it to the
  987. // HTML for the collection view.
  988. addItemView: function(item, ItemView, index){
  989. // get the itemViewOptions if any were specified
  990. var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
  991. if (_.isFunction(itemViewOptions)){
  992. itemViewOptions = itemViewOptions.call(this, item, index);
  993. }
  994. // build the view
  995. var view = this.buildItemView(item, ItemView, itemViewOptions);
  996. // set up the child view event forwarding
  997. this.addChildViewEventForwarding(view);
  998. // this view is about to be added
  999. this.triggerMethod("before:item:added", view);
  1000. // Store the child view itself so we can properly
  1001. // remove and/or close it later
  1002. this.children.add(view);
  1003. // Render it and show it
  1004. this.renderItemView(view, index);
  1005. // call the "show" method if the collection view
  1006. // has already been shown
  1007. if (this._isShown){
  1008. Marionette.triggerMethod.call(view, "show");
  1009. }
  1010. // this view was added
  1011. this.triggerMethod("after:item:added", view);
  1012. },
  1013. // Set up the child view event forwarding. Uses an "itemview:"
  1014. // prefix in front of all forwarded events.
  1015. addChildViewEventForwarding: function(view){
  1016. var prefix = Marionette.getOption(this, "itemViewEventPrefix");
  1017. // Forward all child item view events through the parent,
  1018. // prepending "itemview:" to the event name
  1019. this.listenTo(view, "all", function(){
  1020. var args = slice(arguments);
  1021. args[0] = prefix + ":" + args[0];
  1022. args.splice(1, 0, view);
  1023. Marionette.triggerMethod.apply(this, args);
  1024. }, this);
  1025. },
  1026. // render the item view
  1027. renderItemView: function(view, index) {
  1028. view.render();
  1029. this.appendHtml(this, view, index);
  1030. },
  1031. // Build an `itemView` for every model in the collection.
  1032. buildItemView: function(item, ItemViewType, itemViewOptions){
  1033. var options = _.extend({model: item}, itemViewOptions);
  1034. return new ItemViewType(options);
  1035. },
  1036. // get the child view by item it holds, and remove it
  1037. removeItemView: function(item){
  1038. var view = this.children.findByModel(item);
  1039. this.removeChildView(view);
  1040. this.checkEmpty();
  1041. },
  1042. // Remove the child view and close it
  1043. removeChildView: function(view){
  1044. // shut down the child view properly,
  1045. // including events that the collection has from it
  1046. if (view){
  1047. this.stopListening(view);
  1048. // call 'close' or 'remove', depending on which is found
  1049. if (view.close) { view.close(); }
  1050. else if (view.remove) { view.remove(); }
  1051. this.children.remove(view);
  1052. }
  1053. this.triggerMethod("item:removed", view);
  1054. },
  1055. // helper to show the empty view if the collection is empty
  1056. checkEmpty: function() {
  1057. // check if we're empty now, and if we are, show the
  1058. // empty view
  1059. if (!this.collection || this.collection.length === 0){
  1060. this.showEmptyView();
  1061. }
  1062. },
  1063. // You might need to override this if you've overridden appendHtml
  1064. appendBuffer: function(collectionView, buffer) {
  1065. collectionView.$el.append(buffer);
  1066. },
  1067. // Append the HTML to the collection's `el`.
  1068. // Override this method to do something other
  1069. // then `.append`.
  1070. appendHtml: function(collectionView, itemView, index){
  1071. if (collectionView.isBuffering) {
  1072. // buffering happens on reset events and initial renders
  1073. // in order to reduce the number of inserts into the
  1074. // document, which are expensive.
  1075. collectionView.elBuffer.appendChild(itemView.el);
  1076. }
  1077. else {
  1078. // If we've already rendered the main collection, just
  1079. // append the new items directly into the element.
  1080. collectionView.$el.append(itemView.el);
  1081. }
  1082. },
  1083. // Internal method to set up the `children` object for
  1084. // storing all of the child views
  1085. _initChildViewStorage: function(){
  1086. this.children = new Backbone.ChildViewContainer();
  1087. },
  1088. // Handle cleanup and other closing needs for
  1089. // the collection of views.
  1090. close: function(){
  1091. if (this.isClosed){ return; }
  1092. this.triggerMethod("collection:before:close");
  1093. this.closeChildren();
  1094. this.triggerMethod("collection:closed");
  1095. Marionette.View.prototype.close.apply(this, slice(arguments));
  1096. },
  1097. // Close the child views that this collection view
  1098. // is holding on to, if any
  1099. closeChildren: function(){
  1100. this.children.each(function(child){
  1101. this.removeChildView(child);
  1102. }, this);
  1103. this.checkEmpty();
  1104. }
  1105. });
  1106. // Composite View
  1107. // --------------
  1108. // Used for rendering a branch-leaf, hierarchical structure.
  1109. // Extends directly from CollectionView and also renders an
  1110. // an item view as `modelView`, for the top leaf
  1111. Marionette.CompositeView = Marionette.CollectionView.extend({
  1112. // Setting up the inheritance chain which allows changes to
  1113. // Marionette.CollectionView.prototype.constructor which allows overriding
  1114. constructor: function(){
  1115. Marionette.CollectionView.prototype.constructor.apply(this, slice(arguments));
  1116. },
  1117. // Configured the initial events that the composite view
  1118. // binds to. Override this method to prevent the initial
  1119. // events, or to add your own initial events.
  1120. _initialEvents: function(){
  1121. // Bind only after composite view in rendered to avoid adding child views
  1122. // to unexisting itemViewContainer
  1123. this.once('render', function () {
  1124. if (this.collection){
  1125. this.listenTo(this.collection, "add", this.addChildView, this);
  1126. this.listenTo(this.collection, "remove", this.removeItemView, this);
  1127. this.listenTo(this.collection, "reset", this._renderChildren, this);
  1128. }
  1129. });
  1130. },
  1131. // Retrieve the `itemView` to be used when rendering each of
  1132. // the items in the collection. The default is to return
  1133. // `this.itemView` or Marionette.CompositeView if no `itemView`
  1134. // has been defined
  1135. getItemView: function(item){
  1136. var itemView = Marionette.getOption(this, "itemView") || this.constructor;
  1137. if (!itemView){
  1138. throwError("An `itemView` must be specified", "NoItemViewError");
  1139. }
  1140. return itemView;
  1141. },
  1142. // Serialize the collection for the view.
  1143. // You can override the `serializeData` method in your own view
  1144. // definition, to provide custom serialization for your view's data.
  1145. serializeData: function(){
  1146. var data = {};
  1147. if (this.model){
  1148. data = this.model.toJSON();
  1149. }
  1150. return data;
  1151. },
  1152. // Renders the model once, and the collection once. Calling
  1153. // this again will tell the model's view to re-render itself
  1154. // but the collection will not re-render.
  1155. render: function(){
  1156. this.isRendered = true;
  1157. this.isClosed = false;
  1158. this.resetItemViewContainer();
  1159. this.triggerBeforeRender();
  1160. var html = this.renderModel();
  1161. this.$el.html(html);
  1162. // the ui bindings is done here and not at the end of render since they
  1163. // will not be available until after the model is rendered, but should be
  1164. // available before the collection is rendered.
  1165. this.bindUIElements();
  1166. this.triggerMethod("composite:model:rendered");
  1167. this._renderChildren();
  1168. this.triggerMethod("composite:rendered");
  1169. this.triggerRendered();
  1170. return this;
  1171. },
  1172. _renderChildren: function(){
  1173. if (this.isRendered){
  1174. Marionette.CollectionView.prototype._renderChildren.call(this);
  1175. this.triggerMethod("composite:collection:rendered");
  1176. }
  1177. },
  1178. // Render an individual model, if we have one, as
  1179. // part of a composite view (branch / leaf). For example:
  1180. // a treeview.
  1181. renderModel: function(){
  1182. var data = {};
  1183. data = this.serializeData();
  1184. data = this.mixinTemplateHelpers(data);
  1185. var template = this.getTemplate();
  1186. return Marionette.Renderer.render(template, data);
  1187. },
  1188. // You might need to override this if you've overridden appendHtml
  1189. appendBuffer: function(compositeView, buffer) {
  1190. var $container = this.getItemViewContainer(compositeView);
  1191. $container.append(buffer);
  1192. },
  1193. // Appends the `el` of itemView instances to the specified
  1194. // `itemViewContainer` (a jQuery selector). Override this method to
  1195. // provide custom logic of how the child item view instances have their
  1196. // HTML appended to the composite view instance.
  1197. appendHtml: function(compositeView, itemView, index){
  1198. if (compositeView.isBuffering) {
  1199. compositeView.elBuffer.appendChild(itemView.el);
  1200. }
  1201. else {
  1202. // If we've already rendered the main collection, just
  1203. // append the new items directly into the element.
  1204. var $container = this.getItemViewContainer(compositeView);
  1205. $container.append(itemView.el);
  1206. }
  1207. },
  1208. // Internal method to ensure an `$itemViewContainer` exists, for the
  1209. // `appendHtml` method to use.
  1210. getItemViewContainer: function(containerView){
  1211. if ("$itemViewContainer" in containerView){
  1212. return containerView.$itemViewContainer;
  1213. }
  1214. var container;
  1215. var itemViewContainer = Marionette.getOption(containerView, "itemViewContainer");
  1216. if (itemViewContainer){
  1217. var selector = _.isFunction(itemViewContainer) ? itemViewContainer() : itemViewContainer;
  1218. container = containerView.$(selector);
  1219. if (container.length <= 0) {
  1220. throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
  1221. }
  1222. } else {
  1223. container = containerView.$el;
  1224. }
  1225. containerView.$itemViewContainer = container;
  1226. return container;
  1227. },
  1228. // Internal method to reset the `$itemViewContainer` on render
  1229. resetItemViewContainer: function(){
  1230. if (this.$itemViewContainer){
  1231. delete this.$itemViewContainer;
  1232. }
  1233. }
  1234. });
  1235. // Layout
  1236. // ------
  1237. // Used for managing application layouts, nested layouts and
  1238. // multiple regions within an application or sub-application.
  1239. //
  1240. // A specialized view type that renders an area of HTML and then
  1241. // attaches `Region` instances to the specified `regions`.
  1242. // Used for composite view management and sub-application areas.
  1243. Marionette.Layout = Marionette.ItemView.extend({
  1244. regionType: Marionette.Region,
  1245. // Ensure the regions are available when the `initialize` method
  1246. // is called.
  1247. constructor: function (options) {
  1248. options = options || {};
  1249. this._firstRender = true;
  1250. this._initializeRegions(options);
  1251. Marionette.ItemView.prototype.constructor.call(this, options);
  1252. },
  1253. // Layout's render will use the existing region objects the
  1254. // first time it is called. Subsequent calls will close the
  1255. // views that the regions are showing and then reset the `el`
  1256. // for the regions to the newly rendered DOM elements.
  1257. render: function(){
  1258. if (this.isClosed){
  1259. // a previously closed layout means we need to
  1260. // completely re-initialize the regions
  1261. this._initializeRegions();
  1262. }
  1263. if (this._firstRender) {
  1264. // if this is the first render, don't do anything to
  1265. // reset the regions
  1266. this._firstRender = false;
  1267. } else if (!this.isClosed){
  1268. // If this is not the first render call, then we need to
  1269. // re-initializing the `el` for each region
  1270. this._reInitializeRegions();
  1271. }
  1272. var args = Array.prototype.slice.apply(arguments);
  1273. var result = Marionette.ItemView.prototype.render.apply(this, args);
  1274. return result;
  1275. },
  1276. // Handle closing regions, and then close the view itself.
  1277. close: function () {
  1278. if (this.isClosed){ return; }
  1279. this.regionManager.close();
  1280. var args = Array.prototype.slice.apply(arguments);
  1281. Marionette.ItemView.prototype.close.apply(this, args);
  1282. },
  1283. // Add a single region, by name, to the layout
  1284. addRegion: function(name, definition){
  1285. var regions = {};
  1286. regions[name] = definition;
  1287. return this._buildRegions(regions)[name];
  1288. },
  1289. // Add multiple regions as a {name: definition, name2: def2} object literal
  1290. addRegions: function(regions){
  1291. this.regions = _.extend({}, this.regions, regions);
  1292. return this._buildRegions(regions);
  1293. },
  1294. // Remove a single region from the Layout, by name
  1295. removeRegion: function(name){
  1296. delete this.regions[name];
  1297. return this.regionManager.removeRegion(name);
  1298. },
  1299. // internal method to build regions
  1300. _buildRegions: function(regions){
  1301. var that = this;
  1302. var defaults = {
  1303. regionType: Marionette.getOption(this, "regionType"),
  1304. parentEl: function(){ return that.$el; }
  1305. };
  1306. return this.regionManager.addRegions(regions, defaults);
  1307. },
  1308. // Internal method to initialize the regions that have been defined in a
  1309. // `regions` attribute on this layout.
  1310. _initializeRegions: function (options) {
  1311. var regions;
  1312. this._initRegionManager();
  1313. if (_.isFunction(this.regions)) {
  1314. regions = this.regions(options);
  1315. } else {
  1316. regions = this.regions || {};
  1317. }
  1318. this.addRegions(regions);
  1319. },
  1320. // Internal method to re-initialize all of the regions by updating the `el` that
  1321. // they point to
  1322. _reInitializeRegions: function(){
  1323. this.regionManager.closeRegions();
  1324. this.regionManager.each(function(region){
  1325. region.reset();
  1326. });
  1327. },
  1328. // Internal method to initialize the region manager
  1329. // and all regions in it
  1330. _initRegionManager: function(){
  1331. this.regionManager = new Marionette.RegionManager();
  1332. this.listenTo(this.regionManager, "region:add", function(name, region){
  1333. this[name] = region;
  1334. this.trigger("region:add", name, region);
  1335. });
  1336. this.listenTo(this.regionManager, "region:remove", function(name, region){
  1337. delete this[name];
  1338. this.trigger("region:remove", name, region);
  1339. });
  1340. }
  1341. });
  1342. // AppRouter
  1343. // ---------
  1344. // Reduce the boilerplate code of handling route events
  1345. // and then calling a single method on another object.
  1346. // Have your routers configured to call the method on
  1347. // your object, directly.
  1348. //
  1349. // Configure an AppRouter with `appRoutes`.
  1350. //
  1351. // App routers can only take one `controller` object.
  1352. // It is recommended that you divide your controller
  1353. // objects in to smaller pieces of related functionality
  1354. // and have multiple routers / controllers, instead of
  1355. // just one giant router and controller.
  1356. //

Large files files are truncated, but you can click here to view the full file