PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/ajax/libs/backbone.marionette/0.9.0/amd/backbone.marionette.js

https://gitlab.com/Blueprint-Marketing/cdnjs
JavaScript | 1085 lines | 579 code | 205 blank | 301 comment | 81 complexity | b335e71620b44b62c5a09292b609e3c8 MD5 | raw file
  1. // Backbone.Marionette v0.9.0
  2. //
  3. // Copyright (C)2012 Derick Bailey, Muted Solutions, LLC
  4. // Distributed Under MIT License
  5. //
  6. // Documentation and Full License Available at:
  7. // http://github.com/derickbailey/backbone.marionette
  8. (function (root, factory) {
  9. if (typeof exports === 'object') {
  10. var jquery = require('jquery');
  11. var underscore = require('underscore');
  12. var backbone = require('backbone');
  13. module.exports = factory(jquery, underscore, backbone);
  14. } else if (typeof define === 'function' && define.amd) {
  15. define(['jquery', 'underscore', 'backbone'], factory);
  16. }
  17. }(this, function ($, _, Backbone) {
  18. Backbone.Marionette = (function(Backbone, _, $){
  19. var Marionette = {};
  20. // BindTo: Event Binding
  21. // ---------------------
  22. // BindTo facilitates the binding and unbinding of events
  23. // from objects that extend `Backbone.Events`. It makes
  24. // unbinding events, even with anonymous callback functions,
  25. // easy.
  26. //
  27. // Thanks to Johnny Oshika for this code.
  28. // http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853#7607853
  29. Marionette.BindTo = {
  30. // Store the event binding in array so it can be unbound
  31. // easily, at a later point in time.
  32. bindTo: function (obj, eventName, callback, context) {
  33. context = context || this;
  34. obj.on(eventName, callback, context);
  35. if (!this.bindings) { this.bindings = []; }
  36. var binding = {
  37. obj: obj,
  38. eventName: eventName,
  39. callback: callback,
  40. context: context
  41. }
  42. this.bindings.push(binding);
  43. return binding;
  44. },
  45. // Unbind from a single binding object. Binding objects are
  46. // returned from the `bindTo` method call.
  47. unbindFrom: function(binding){
  48. binding.obj.off(binding.eventName, binding.callback, binding.context);
  49. this.bindings = _.reject(this.bindings, function(bind){return bind === binding});
  50. },
  51. // Unbind all of the events that we have stored.
  52. unbindAll: function () {
  53. var that = this;
  54. // The `unbindFrom` call removes elements from the array
  55. // while it is being iterated, so clone it first.
  56. var bindings = _.map(this.bindings, _.identity);
  57. _.each(bindings, function (binding, index) {
  58. that.unbindFrom(binding);
  59. });
  60. }
  61. };
  62. // Marionette.View
  63. // ---------------
  64. // The core view type that other Marionette views extend from.
  65. Marionette.View = Backbone.View.extend({
  66. constructor: function(){
  67. Backbone.View.prototype.constructor.apply(this, arguments);
  68. this.bindTo(this, "show", this.onShowCalled, this);
  69. },
  70. // Get the template for this view
  71. // instance. You can set a `template` attribute in the view
  72. // definition or pass a `template: "whatever"` parameter in
  73. // to the constructor options.
  74. getTemplate: function(){
  75. var template;
  76. // Get the template from `this.options.template` or
  77. // `this.template`. The `options` takes precedence.
  78. if (this.options && this.options.template){
  79. template = this.options.template;
  80. } else {
  81. template = this.template;
  82. }
  83. return template;
  84. },
  85. // Serialize the model or collection for the view. If a model is
  86. // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
  87. // is also called, but is used to populate an `items` array in the
  88. // resulting data. If both are found, defaults to the model.
  89. // You can override the `serializeData` method in your own view
  90. // definition, to provide custom serialization for your view's data.
  91. serializeData: function(){
  92. var data;
  93. if (this.model) {
  94. data = this.model.toJSON();
  95. }
  96. else if (this.collection) {
  97. data = { items: this.collection.toJSON() };
  98. }
  99. data = this.mixinTemplateHelpers(data);
  100. return data;
  101. },
  102. // Mix in template helper methods. Looks for a
  103. // `templateHelpers` attribute, which can either be an
  104. // object literal, or a function that returns an object
  105. // literal. All methods and attributes from this object
  106. // are copies to the object passed in.
  107. mixinTemplateHelpers: function(target){
  108. target = target || {};
  109. var templateHelpers = this.templateHelpers;
  110. if (_.isFunction(templateHelpers)){
  111. templateHelpers = templateHelpers.call(this);
  112. }
  113. return _.extend(target, templateHelpers);
  114. },
  115. // Configure `triggers` to forward DOM events to view
  116. // events. `triggers: {"click .foo": "do:foo"}`
  117. configureTriggers: function(){
  118. if (!this.triggers) { return; }
  119. var triggers = this.triggers;
  120. var that = this;
  121. var triggerEvents = {};
  122. // Allow `triggers` to be configured as a function
  123. if (_.isFunction(triggers)){ triggers = triggers.call(this); }
  124. // Configure the triggers, prevent default
  125. // action and stop propagation of DOM events
  126. _.each(triggers, function(value, key){
  127. triggerEvents[key] = function(e){
  128. if (e && e.preventDefault){ e.preventDefault(); }
  129. if (e && e.stopPropagation){ e.stopPropagation(); }
  130. that.trigger(value);
  131. }
  132. });
  133. return triggerEvents;
  134. },
  135. // Overriding Backbone.View's delegateEvents specifically
  136. // to handle the `triggers` configuration
  137. delegateEvents: function(events){
  138. events = events || this.events;
  139. if (_.isFunction(events)){ events = events.call(this)}
  140. var combinedEvents = {};
  141. var triggers = this.configureTriggers();
  142. _.extend(combinedEvents, events, triggers);
  143. Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
  144. },
  145. // Internal method, handles the `show` event.
  146. onShowCalled: function(){},
  147. // Default `close` implementation, for removing a view from the
  148. // DOM and unbinding it. Regions will call this method
  149. // for you. You can specify an `onClose` method in your view to
  150. // add custom code that is called after the view is closed.
  151. close: function(){
  152. if (this.beforeClose) { this.beforeClose(); }
  153. this.remove();
  154. if (this.onClose) { this.onClose(); }
  155. this.trigger('close');
  156. this.unbindAll();
  157. this.unbind();
  158. }
  159. });
  160. // Copy the features of `BindTo`
  161. _.extend(Marionette.View.prototype, Marionette.BindTo);
  162. // Item View
  163. // ---------
  164. // A single item view implementation that contains code for rendering
  165. // with underscore.js templates, serializing the view's model or collection,
  166. // and calling several methods on extended views, such as `onRender`.
  167. Marionette.ItemView = Marionette.View.extend({
  168. constructor: function(){
  169. Marionette.View.prototype.constructor.apply(this, arguments);
  170. this.initialEvents();
  171. },
  172. // Configured the initial events that the item view
  173. // binds to. Override this method to prevent the initial
  174. // events, or to add your own initial events.
  175. initialEvents: function(){
  176. if (this.collection){
  177. this.bindTo(this.collection, "reset", this.render, this);
  178. }
  179. },
  180. // Render the view, defaulting to underscore.js templates.
  181. // You can override this in your view definition to provide
  182. // a very specific rendering for your view. In general, though,
  183. // you should override the `Marionette.Renderer` object to
  184. // change how Marionette renders views.
  185. render: function(){
  186. if (this.beforeRender){ this.beforeRender(); }
  187. this.trigger("before:render", this);
  188. this.trigger("item:before:render", this);
  189. var data = this.serializeData();
  190. var template = this.getTemplate();
  191. var html = Marionette.Renderer.render(template, data);
  192. this.$el.html(html);
  193. if (this.onRender){ this.onRender(); }
  194. this.trigger("render", this);
  195. this.trigger("item:rendered", this);
  196. },
  197. // Override the default close event to add a few
  198. // more events that are triggered.
  199. close: function(){
  200. this.trigger('item:before:close');
  201. Marionette.View.prototype.close.apply(this, arguments);
  202. this.trigger('item:closed');
  203. }
  204. });
  205. // Collection View
  206. // ---------------
  207. // A view that iterates over a Backbone.Collection
  208. // and renders an individual ItemView for each model.
  209. Marionette.CollectionView = Marionette.View.extend({
  210. constructor: function(){
  211. Marionette.View.prototype.constructor.apply(this, arguments);
  212. this.initChildViewStorage();
  213. this.initialEvents();
  214. this.onShowCallbacks = new Marionette.Callbacks();
  215. },
  216. // Configured the initial events that the collection view
  217. // binds to. Override this method to prevent the initial
  218. // events, or to add your own initial events.
  219. initialEvents: function(){
  220. if (this.collection){
  221. this.bindTo(this.collection, "add", this.addChildView, this);
  222. this.bindTo(this.collection, "remove", this.removeItemView, this);
  223. this.bindTo(this.collection, "reset", this.render, this);
  224. }
  225. },
  226. // Handle a child item added to the collection
  227. addChildView: function(item, collection, options){
  228. var ItemView = this.getItemView();
  229. return this.addItemView(item, ItemView, options.index);
  230. },
  231. // Override from `Marionette.View` to guarantee the `onShow` method
  232. // of child views is called.
  233. onShowCalled: function(){
  234. this.onShowCallbacks.run();
  235. },
  236. // Loop through all of the items and render
  237. // each of them with the specified `itemView`.
  238. render: function(){
  239. var that = this;
  240. var ItemView = this.getItemView();
  241. var EmptyView = this.options.emptyView || this.emptyView;
  242. if (this.beforeRender) { this.beforeRender(); }
  243. this.trigger("collection:before:render", this);
  244. this.closeChildren();
  245. if (this.collection) {
  246. if (this.collection.length === 0 && EmptyView) {
  247. this.addItemView(new Backbone.Model(), EmptyView, 0);
  248. } else {
  249. this.collection.each(function(item, index){
  250. that.addItemView(item, ItemView, index);
  251. });
  252. }
  253. }
  254. if (this.onRender) { this.onRender(); }
  255. this.trigger("collection:rendered", this);
  256. },
  257. // Retrieve the itemView type, either from `this.options.itemView`
  258. // or from the `itemView` in the object definition. The "options"
  259. // takes precedence.
  260. getItemView: function(){
  261. var itemView = this.options.itemView || this.itemView;
  262. if (!itemView){
  263. var err = new Error("An `itemView` must be specified");
  264. err.name = "NoItemViewError";
  265. throw err;
  266. }
  267. return itemView;
  268. },
  269. // Render the child item's view and add it to the
  270. // HTML for the collection view.
  271. addItemView: function(item, ItemView, index){
  272. var that = this;
  273. var view = this.buildItemView(item, ItemView);
  274. // Store the child view itself so we can properly
  275. // remove and/or close it later
  276. this.storeChild(view);
  277. if (this.onItemAdded){ this.onItemAdded(view); }
  278. this.trigger("item:added", view);
  279. // Render it and show it
  280. var renderResult = this.renderItemView(view, index);
  281. // call onShow for child item views
  282. if (view.onShow){
  283. this.onShowCallbacks.add(view.onShow, view);
  284. }
  285. // Forward all child item view events through the parent,
  286. // prepending "itemview:" to the event name
  287. var childBinding = this.bindTo(view, "all", function(){
  288. var args = slice.call(arguments);
  289. args[0] = "itemview:" + args[0];
  290. args.splice(1, 0, view);
  291. that.trigger.apply(that, args);
  292. });
  293. // Store all child event bindings so we can unbind
  294. // them when removing / closing the child view
  295. this.childBindings = this.childBindings || {};
  296. this.childBindings[view.cid] = childBinding;
  297. return renderResult;
  298. },
  299. // render the item view
  300. renderItemView: function(view, index) {
  301. view.render();
  302. this.appendHtml(this, view, index);
  303. },
  304. // Build an `itemView` for every model in the collection.
  305. buildItemView: function(item, ItemView){
  306. var itemViewOptions = _.result(this, "itemViewOptions");
  307. var options = _.extend({model: item}, itemViewOptions);
  308. var view = new ItemView(options);
  309. return view;
  310. },
  311. // Remove the child view and close it
  312. removeItemView: function(item){
  313. var view = this.children[item.cid];
  314. if (view){
  315. var childBinding = this.childBindings[view.cid];
  316. if (childBinding) {
  317. this.unbindFrom(childBinding);
  318. delete this.childBindings[view.cid];
  319. }
  320. view.close();
  321. delete this.children[item.cid];
  322. }
  323. this.trigger("item:removed", view);
  324. },
  325. // Append the HTML to the collection's `el`.
  326. // Override this method to do something other
  327. // then `.append`.
  328. appendHtml: function(collectionView, itemView, index){
  329. collectionView.$el.append(itemView.el);
  330. },
  331. // Store references to all of the child `itemView`
  332. // instances so they can be managed and cleaned up, later.
  333. storeChild: function(view){
  334. this.children[view.model.cid] = view;
  335. },
  336. // Internal method to set up the `children` object for
  337. // storing all of the child views
  338. initChildViewStorage: function(){
  339. this.children = {};
  340. },
  341. // Handle cleanup and other closing needs for
  342. // the collection of views.
  343. close: function(){
  344. this.trigger("collection:before:close");
  345. this.closeChildren();
  346. Marionette.View.prototype.close.apply(this, arguments);
  347. this.trigger("collection:closed");
  348. },
  349. // Close the child views that this collection view
  350. // is holding on to, if any
  351. closeChildren: function(){
  352. var that = this;
  353. if (this.children){
  354. _.each(_.clone(this.children), function(childView){
  355. that.removeItemView(childView.model);
  356. });
  357. }
  358. }
  359. });
  360. // Composite View
  361. // --------------
  362. // Used for rendering a branch-leaf, hierarchical structure.
  363. // Extends directly from CollectionView and also renders an
  364. // an item view as `modelView`, for the top leaf
  365. Marionette.CompositeView = Marionette.CollectionView.extend({
  366. constructor: function(options){
  367. Marionette.CollectionView.apply(this, arguments);
  368. this.itemView = this.getItemView();
  369. },
  370. // Configured the initial events that the composite view
  371. // binds to. Override this method to prevent the initial
  372. // events, or to add your own initial events.
  373. initialEvents: function(){
  374. if (this.collection){
  375. this.bindTo(this.collection, "add", this.addChildView, this);
  376. this.bindTo(this.collection, "remove", this.removeItemView, this);
  377. this.bindTo(this.collection, "reset", this.renderCollection, this);
  378. }
  379. },
  380. // Retrieve the `itemView` to be used when rendering each of
  381. // the items in the collection. The default is to return
  382. // `this.itemView` or Marionette.CompositeView if no `itemView`
  383. // has been defined
  384. getItemView: function(){
  385. return this.itemView || this.constructor;
  386. },
  387. // Renders the model once, and the collection once. Calling
  388. // this again will tell the model's view to re-render itself
  389. // but the collection will not re-render.
  390. render: function(){
  391. var that = this;
  392. var html = this.renderModel();
  393. this.$el.html(html);
  394. this.trigger("composite:model:rendered");
  395. this.trigger("render");
  396. this.renderCollection();
  397. this.trigger("composite:rendered");
  398. },
  399. // Render the collection for the composite view
  400. renderCollection: function(){
  401. Marionette.CollectionView.prototype.render.apply(this, arguments);
  402. this.trigger("composite:collection:rendered");
  403. },
  404. // Render an individual model, if we have one, as
  405. // part of a composite view (branch / leaf). For example:
  406. // a treeview.
  407. renderModel: function(){
  408. var data = {};
  409. data = this.serializeData();
  410. var template = this.getTemplate();
  411. return Marionette.Renderer.render(template, data);
  412. }
  413. });
  414. // Region
  415. // ------
  416. // Manage the visual regions of your composite application. See
  417. // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
  418. Marionette.Region = function(options){
  419. this.options = options || {};
  420. _.extend(this, options);
  421. if (!this.el){
  422. var err = new Error("An 'el' must be specified");
  423. err.name = "NoElError";
  424. throw err;
  425. }
  426. if (this.initialize){
  427. this.initialize.apply(this, arguments);
  428. }
  429. };
  430. _.extend(Marionette.Region.prototype, Backbone.Events, {
  431. // Displays a backbone view instance inside of the region.
  432. // Handles calling the `render` method for you. Reads content
  433. // directly from the `el` attribute. Also calls an optional
  434. // `onShow` and `close` method on your view, just after showing
  435. // or just before closing the view, respectively.
  436. show: function(view){
  437. var that = this;
  438. this.ensureEl();
  439. this.close();
  440. view.render();
  441. this.open(view);
  442. if (view.onShow) { view.onShow(); }
  443. view.trigger("show");
  444. if (this.onShow) { this.onShow(view); }
  445. this.trigger("view:show", view);
  446. this.currentView = view;
  447. },
  448. ensureEl: function(){
  449. if (!this.$el || this.$el.length === 0){
  450. this.$el = this.getEl(this.el);
  451. }
  452. },
  453. // Override this method to change how the region finds the
  454. // DOM element that it manages. Return a jQuery selector object.
  455. getEl: function(selector){
  456. return $(selector);
  457. },
  458. // Override this method to change how the new view is
  459. // appended to the `$el` that the region is managing
  460. open: function(view){
  461. this.$el.html(view.el);
  462. },
  463. // Close the current view, if there is one. If there is no
  464. // current view, it does nothing and returns immediately.
  465. close: function(){
  466. var view = this.currentView;
  467. if (!view){ return; }
  468. if (view.close) { view.close(); }
  469. this.trigger("view:closed", view);
  470. delete this.currentView;
  471. },
  472. // Attach an existing view to the region. This
  473. // will not call `render` or `onShow` for the new view,
  474. // and will not replace the current HTML for the `el`
  475. // of the region.
  476. attachView: function(view){
  477. this.currentView = view;
  478. }
  479. });
  480. // Copy the `extend` function used by Backbone's classes
  481. Marionette.Region.extend = Backbone.View.extend;
  482. // Copy the features of `BindTo`
  483. _.extend(Marionette.Region.prototype, Marionette.BindTo);
  484. // Layout
  485. // ------
  486. // Used for managing application layouts, nested layouts and
  487. // multiple regions within an application or sub-application.
  488. //
  489. // A specialized view type that renders an area of HTML and then
  490. // attaches `Region` instances to the specified `regions`.
  491. // Used for composite view management and sub-application areas.
  492. Marionette.Layout = Marionette.ItemView.extend({
  493. constructor: function () {
  494. Backbone.Marionette.ItemView.apply(this, arguments);
  495. this.initializeRegions();
  496. },
  497. // Layout's render will use the existing region objects the
  498. // first time it is called. Subsequent calls will close the
  499. // views that the regions are showing and then reset the `el`
  500. // for the regions to the newly rendered DOM elements.
  501. render: function(){
  502. var result = Marionette.ItemView.prototype.render.apply(this, arguments);
  503. // Rewrite this function to handle re-rendering and
  504. // re-initializing the `el` for each region
  505. this.render = function(){
  506. this.closeRegions();
  507. this.reInitializeRegions();
  508. var result = Marionette.ItemView.prototype.render.apply(this, arguments);
  509. return result;
  510. }
  511. return result;
  512. },
  513. // Handle closing regions, and then close the view itself.
  514. close: function () {
  515. this.closeRegions();
  516. this.destroyRegions();
  517. Backbone.Marionette.ItemView.prototype.close.call(this, arguments);
  518. },
  519. // Initialize the regions that have been defined in a
  520. // `regions` attribute on this layout. The key of the
  521. // hash becomes an attribute on the layout object directly.
  522. // For example: `regions: { menu: ".menu-container" }`
  523. // will product a `layout.menu` object which is a region
  524. // that controls the `.menu-container` DOM element.
  525. initializeRegions: function () {
  526. if (!this.regionManagers){
  527. this.regionManagers = {};
  528. }
  529. var that = this;
  530. _.each(this.regions, function (selector, name) {
  531. var regionManager = new Backbone.Marionette.Region({
  532. el: selector,
  533. getEl: function(selector){
  534. return that.$(selector);
  535. }
  536. });
  537. that.regionManagers[name] = regionManager;
  538. that[name] = regionManager;
  539. });
  540. },
  541. // Re-initialize all of the regions by updating the `el` that
  542. // they point to
  543. reInitializeRegions: function(){
  544. _.each(this.regionManagers, function(region){
  545. delete region.$el;
  546. });
  547. },
  548. // Close all of the regions that have been opened by
  549. // this layout. This method is called when the layout
  550. // itself is closed.
  551. closeRegions: function () {
  552. var that = this;
  553. _.each(this.regionManagers, function (manager, name) {
  554. manager.close();
  555. });
  556. },
  557. // Destroys all of the regions by removing references
  558. // from the Layout
  559. destroyRegions: function(){
  560. var that = this;
  561. _.each(this.regionManagers, function (manager, name) {
  562. delete that[name];
  563. });
  564. this.regionManagers = {};
  565. }
  566. });
  567. // Application
  568. // -----------
  569. // Contain and manage the composite application as a whole.
  570. // Stores and starts up `Region` objects, includes an
  571. // event aggregator as `app.vent`
  572. Marionette.Application = function(options){
  573. this.initCallbacks = new Marionette.Callbacks();
  574. this.vent = new Marionette.EventAggregator();
  575. _.extend(this, options);
  576. };
  577. _.extend(Marionette.Application.prototype, Backbone.Events, {
  578. // Add an initializer that is either run at when the `start`
  579. // method is called, or run immediately if added after `start`
  580. // has already been called.
  581. addInitializer: function(initializer){
  582. this.initCallbacks.add(initializer);
  583. },
  584. // kick off all of the application's processes.
  585. // initializes all of the regions that have been added
  586. // to the app, and runs all of the initializer functions
  587. start: function(options){
  588. this.trigger("initialize:before", options);
  589. this.initCallbacks.run(options, this);
  590. this.trigger("initialize:after", options);
  591. this.trigger("start", options);
  592. },
  593. // Add regions to your app.
  594. // Accepts a hash of named strings or Region objects
  595. // addRegions({something: "#someRegion"})
  596. // addRegions{{something: Region.extend({el: "#someRegion"}) });
  597. addRegions: function(regions){
  598. var regionValue, regionObj, region;
  599. for(region in regions){
  600. if (regions.hasOwnProperty(region)){
  601. regionValue = regions[region];
  602. if (typeof regionValue === "string"){
  603. regionObj = new Marionette.Region({
  604. el: regionValue
  605. });
  606. } else {
  607. regionObj = new regionValue();
  608. }
  609. this[region] = regionObj;
  610. }
  611. }
  612. },
  613. // Create a module, attached to the application
  614. module: function(){
  615. // see the Marionette.Module object for more information
  616. return Marionette.Module.create.apply(this, arguments);
  617. }
  618. });
  619. // Copy the `extend` function used by Backbone's classes
  620. Marionette.Application.extend = Backbone.View.extend;
  621. // Copy the features of `BindTo`
  622. _.extend(Marionette.Application.prototype, Marionette.BindTo);
  623. // AppRouter
  624. // ---------
  625. // Reduce the boilerplate code of handling route events
  626. // and then calling a single method on another object.
  627. // Have your routers configured to call the method on
  628. // your object, directly.
  629. //
  630. // Configure an AppRouter with `appRoutes`.
  631. //
  632. // App routers can only take one `controller` object.
  633. // It is recommended that you divide your controller
  634. // objects in to smaller peices of related functionality
  635. // and have multiple routers / controllers, instead of
  636. // just one giant router and controller.
  637. //
  638. // You can also add standard routes to an AppRouter.
  639. Marionette.AppRouter = Backbone.Router.extend({
  640. constructor: function(options){
  641. Backbone.Router.prototype.constructor.call(this, options);
  642. if (this.appRoutes){
  643. var controller = this.controller;
  644. if (options && options.controller) {
  645. controller = options.controller;
  646. }
  647. this.processAppRoutes(controller, this.appRoutes);
  648. }
  649. },
  650. // Internal method to process the `appRoutes` for the
  651. // router, and turn them in to routes that trigger the
  652. // specified method on the specified `controller`.
  653. processAppRoutes: function(controller, appRoutes){
  654. var method, methodName;
  655. var route, routesLength, i;
  656. var routes = [];
  657. var router = this;
  658. for(route in appRoutes){
  659. if (appRoutes.hasOwnProperty(route)){
  660. routes.unshift([route, appRoutes[route]]);
  661. }
  662. }
  663. routesLength = routes.length;
  664. for (i = 0; i < routesLength; i++){
  665. route = routes[i][0];
  666. methodName = routes[i][1];
  667. method = controller[methodName];
  668. if (!method){
  669. var msg = "Method '" + methodName + "' was not found on the controller";
  670. var err = new Error(msg);
  671. err.name = "NoMethodError";
  672. throw err;
  673. }
  674. method = _.bind(method, controller);
  675. router.route(route, methodName, method);
  676. }
  677. }
  678. });
  679. // Module
  680. // ------
  681. // A simple module system, used to create privacy and encapsulation in
  682. // Marionette applications
  683. Marionette.Module = function(){};
  684. // Extend the Module prototype with events / bindTo, so that the module
  685. // can be used as an event aggregator or pub/sub.
  686. _.extend(Marionette.Module.prototype, Backbone.Events, Marionette.BindTo);
  687. // Function level methods to create modules
  688. _.extend(Marionette.Module, {
  689. // Create a module, hanging off 'this' as the parent object. This
  690. // method must be called with .apply or .create
  691. create: function(moduleNames, moduleDefinition){
  692. var moduleName, module, moduleOverride;
  693. var parentObject = this;
  694. var parentModule = this;
  695. var moduleNames = moduleNames.split(".");
  696. // Loop through all the parts of the module definition
  697. var length = moduleNames.length;
  698. for(var i = 0; i < length; i++){
  699. var isLastModuleInChain = (i === length-1);
  700. // Get the module name, and check if it exists on
  701. // the current parent already
  702. moduleName = moduleNames[i];
  703. module = parentModule[moduleName];
  704. // Create a new module if we don't have one already
  705. if (!module){
  706. module = new Marionette.Module();
  707. }
  708. // Check to see if we need to run the definition
  709. // for the module. Only run the definition if one
  710. // is supplied, and if we're at the last segment
  711. // of the "Module.Name" chain.
  712. if (isLastModuleInChain && moduleDefinition){
  713. // get the custom args passed in after the module definition and
  714. // get rid of the module name and definition function
  715. var customArgs = slice.apply(arguments);
  716. customArgs.shift();
  717. customArgs.shift();
  718. // final arguments list for the module definition
  719. var argsArray = [module, parentObject, Backbone, Marionette, jQuery, _, customArgs];
  720. // flatten the nested array
  721. var args = _.flatten(argsArray);
  722. // ensure the module definition's `this` is the module itself
  723. moduleDefinition.apply(module, args);
  724. }
  725. // If the defined module is not what we are
  726. // currently storing as the module, replace it
  727. if (parentModule[moduleName] !== module){
  728. parentModule[moduleName] = module;
  729. }
  730. // Reset the parent module so that the next child
  731. // in the list will be added to the correct parent
  732. parentModule = module;
  733. }
  734. // Return the last module in the definition chain
  735. return module;
  736. }
  737. });
  738. // Template Cache
  739. // --------------
  740. // Manage templates stored in `<script>` blocks,
  741. // caching them for faster access.
  742. Marionette.TemplateCache = function(templateId){
  743. this.templateId = templateId;
  744. };
  745. // TemplateCache object-level methods. Manage the template
  746. // caches from these method calls instead of creating
  747. // your own TemplateCache instances
  748. _.extend(Marionette.TemplateCache, {
  749. templateCaches: {},
  750. // Get the specified template by id. Either
  751. // retrieves the cached version, or loads it
  752. // from the DOM.
  753. get: function(templateId){
  754. var that = this;
  755. var cachedTemplate = this.templateCaches[templateId];
  756. if (!cachedTemplate){
  757. cachedTemplate = new Marionette.TemplateCache(templateId);
  758. this.templateCaches[templateId] = cachedTemplate;
  759. }
  760. return cachedTemplate.load();
  761. },
  762. // Clear templates from the cache. If no arguments
  763. // are specified, clears all templates:
  764. // `clear()`
  765. //
  766. // If arguments are specified, clears each of the
  767. // specified templates from the cache:
  768. // `clear("#t1", "#t2", "...")`
  769. clear: function(){
  770. var i;
  771. var length = arguments.length;
  772. if (length > 0){
  773. for(i=0; i<length; i++){
  774. delete this.templateCaches[arguments[i]];
  775. }
  776. } else {
  777. this.templateCaches = {};
  778. }
  779. }
  780. });
  781. // TemplateCache instance methods, allowing each
  782. // template cache object to manage it's own state
  783. // and know whether or not it has been loaded
  784. _.extend(Marionette.TemplateCache.prototype, {
  785. // Internal method to load the template asynchronously.
  786. load: function(){
  787. var that = this;
  788. // Guard clause to prevent loading this template more than once
  789. if (this.compiledTemplate){
  790. return this.compiledTemplate;
  791. }
  792. // Load the template and compile it
  793. var template = this.loadTemplate(this.templateId);
  794. this.compiledTemplate = this.compileTemplate(template);
  795. return this.compiledTemplate;
  796. },
  797. // Load a template from the DOM, by default. Override
  798. // this method to provide your own template retrieval,
  799. // such as asynchronous loading from a server.
  800. loadTemplate: function(templateId){
  801. var template = $(templateId).html();
  802. if (!template || template.length === 0){
  803. var msg = "Could not find template: '" + templateId + "'";
  804. var err = new Error(msg);
  805. err.name = "NoTemplateError";
  806. throw err;
  807. }
  808. return template;
  809. },
  810. // Pre-compile the template before caching it. Override
  811. // this method if you do not need to pre-compile a template
  812. // (JST / RequireJS for example) or if you want to change
  813. // the template engine used (Handebars, etc).
  814. compileTemplate: function(rawTemplate){
  815. return _.template(rawTemplate);
  816. }
  817. });
  818. // Renderer
  819. // --------
  820. // Render a template with data by passing in the template
  821. // selector and the data to render.
  822. Marionette.Renderer = {
  823. // Render a template with data. The `template` parameter is
  824. // passed to the `TemplateCache` object to retrieve the
  825. // template function. Override this method to provide your own
  826. // custom rendering and template handling for all of Marionette.
  827. render: function(template, data){
  828. var templateFunc = Marionette.TemplateCache.get(template);
  829. var html = templateFunc(data);
  830. return html;
  831. }
  832. };
  833. // Callbacks
  834. // ---------
  835. // A simple way of managing a collection of callbacks
  836. // and executing them at a later point in time, using jQuery's
  837. // `Deferred` object.
  838. Marionette.Callbacks = function(){
  839. this.deferred = $.Deferred();
  840. this.promise = this.deferred.promise();
  841. };
  842. _.extend(Marionette.Callbacks.prototype, {
  843. // Add a callback to be executed. Callbacks added here are
  844. // guaranteed to execute, even if they are added after the
  845. // `run` method is called.
  846. add: function(callback, contextOverride){
  847. this.promise.done(function(context, options){
  848. if (contextOverride){ context = contextOverride; }
  849. callback.call(context, options);
  850. });
  851. },
  852. // Run all registered callbacks with the context specified.
  853. // Additional callbacks can be added after this has been run
  854. // and they will still be executed.
  855. run: function(options, context){
  856. this.deferred.resolve(context, options);
  857. }
  858. });
  859. // Event Aggregator
  860. // ----------------
  861. // A pub-sub object that can be used to decouple various parts
  862. // of an application through event-driven architecture.
  863. Marionette.EventAggregator = function(options){
  864. _.extend(this, options);
  865. };
  866. _.extend(Marionette.EventAggregator.prototype, Backbone.Events, Marionette.BindTo, {
  867. // Assumes the event aggregator itself is the
  868. // object being bound to.
  869. bindTo: function(eventName, callback, context){
  870. return Marionette.BindTo.bindTo.call(this, this, eventName, callback, context);
  871. }
  872. });
  873. // Helpers
  874. // -------
  875. // For slicing `arguments` in functions
  876. var slice = Array.prototype.slice;
  877. return Marionette;
  878. })(Backbone, _, window.jQuery || window.Zepto || window.ender);
  879. return Backbone.Marionette;
  880. }));