PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/client/requires/backbone.marionette/js/backbone.marionette.js

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

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