PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/Blueprint-Marketing/cdnjs
JavaScript | 1127 lines | 603 code | 210 blank | 314 comment | 83 complexity | fa84eadce4a1d9f8e94367d2d1c1fdbe MD5 | raw file
  1. // Backbone.Marionette v0.9.1
  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. this.closeEmptyView();
  229. var ItemView = this.getItemView();
  230. return this.addItemView(item, ItemView, options.index);
  231. },
  232. // Override from `Marionette.View` to guarantee the `onShow` method
  233. // of child views is called.
  234. onShowCalled: function(){
  235. this.onShowCallbacks.run();
  236. },
  237. // Internal method to trigger the before render callbacks
  238. // and events
  239. triggerBeforeRender: function(){
  240. if (this.beforeRender) { this.beforeRender(); }
  241. this.trigger("collection:before:render", this);
  242. },
  243. // Internal method to trigger the rendered callbacks and
  244. // events
  245. triggerRendered: function(){
  246. if (this.onRender) { this.onRender(); }
  247. this.trigger("collection:rendered", this);
  248. },
  249. // Render the collection of items. Override this method to
  250. // provide your own implementation of a render function for
  251. // the collection view.
  252. render: function(){
  253. this.triggerBeforeRender();
  254. this.closeChildren();
  255. if (this.collection && this.collection.length > 0) {
  256. this.showCollection();
  257. } else {
  258. this.showEmptyView();
  259. }
  260. this.triggerRendered();
  261. },
  262. // Internal method to loop through each item in the
  263. // collection view and show it
  264. showCollection: function(){
  265. var that = this;
  266. var ItemView = this.getItemView();
  267. this.collection.each(function(item, index){
  268. that.addItemView(item, ItemView, index);
  269. });
  270. },
  271. // Internal method to show an empty view in place of
  272. // a collection of item views, when the collection is
  273. // empty
  274. showEmptyView: function(){
  275. var EmptyView = this.options.emptyView || this.emptyView;
  276. if (EmptyView){
  277. this.showingEmptyView = true;
  278. var model = new Backbone.Model();
  279. this.addItemView(model, EmptyView, 0);
  280. }
  281. },
  282. // Internal method to close an existing emptyView instance
  283. // if one exists. Called when a collection view has been
  284. // rendered empty, and then an item is added to the collection.
  285. closeEmptyView: function(){
  286. if (this.showingEmptyView){
  287. this.closeChildren();
  288. delete this.showingEmptyView;
  289. }
  290. },
  291. // Retrieve the itemView type, either from `this.options.itemView`
  292. // or from the `itemView` in the object definition. The "options"
  293. // takes precedence.
  294. getItemView: function(){
  295. var itemView = this.options.itemView || this.itemView;
  296. if (!itemView){
  297. var err = new Error("An `itemView` must be specified");
  298. err.name = "NoItemViewError";
  299. throw err;
  300. }
  301. return itemView;
  302. },
  303. // Render the child item's view and add it to the
  304. // HTML for the collection view.
  305. addItemView: function(item, ItemView, index){
  306. var that = this;
  307. var view = this.buildItemView(item, ItemView);
  308. // Store the child view itself so we can properly
  309. // remove and/or close it later
  310. this.storeChild(view);
  311. if (this.onItemAdded){ this.onItemAdded(view); }
  312. this.trigger("item:added", view);
  313. // Render it and show it
  314. var renderResult = this.renderItemView(view, index);
  315. // call onShow for child item views
  316. if (view.onShow){
  317. this.onShowCallbacks.add(view.onShow, view);
  318. }
  319. // Forward all child item view events through the parent,
  320. // prepending "itemview:" to the event name
  321. var childBinding = this.bindTo(view, "all", function(){
  322. var args = slice.call(arguments);
  323. args[0] = "itemview:" + args[0];
  324. args.splice(1, 0, view);
  325. that.trigger.apply(that, args);
  326. });
  327. // Store all child event bindings so we can unbind
  328. // them when removing / closing the child view
  329. this.childBindings = this.childBindings || {};
  330. this.childBindings[view.cid] = childBinding;
  331. return renderResult;
  332. },
  333. // render the item view
  334. renderItemView: function(view, index) {
  335. view.render();
  336. this.appendHtml(this, view, index);
  337. },
  338. // Build an `itemView` for every model in the collection.
  339. buildItemView: function(item, ItemView){
  340. var itemViewOptions = _.result(this, "itemViewOptions");
  341. var options = _.extend({model: item}, itemViewOptions);
  342. var view = new ItemView(options);
  343. return view;
  344. },
  345. // Remove the child view and close it
  346. removeItemView: function(item){
  347. var view = this.children[item.cid];
  348. if (view){
  349. var childBinding = this.childBindings[view.cid];
  350. if (childBinding) {
  351. this.unbindFrom(childBinding);
  352. delete this.childBindings[view.cid];
  353. }
  354. view.close();
  355. delete this.children[item.cid];
  356. }
  357. if (this.collection.length === 0){
  358. this.showEmptyView();
  359. }
  360. this.trigger("item:removed", view);
  361. },
  362. // Append the HTML to the collection's `el`.
  363. // Override this method to do something other
  364. // then `.append`.
  365. appendHtml: function(collectionView, itemView, index){
  366. collectionView.$el.append(itemView.el);
  367. },
  368. // Store references to all of the child `itemView`
  369. // instances so they can be managed and cleaned up, later.
  370. storeChild: function(view){
  371. this.children[view.model.cid] = view;
  372. },
  373. // Internal method to set up the `children` object for
  374. // storing all of the child views
  375. initChildViewStorage: function(){
  376. this.children = {};
  377. },
  378. // Handle cleanup and other closing needs for
  379. // the collection of views.
  380. close: function(){
  381. this.trigger("collection:before:close");
  382. this.closeChildren();
  383. Marionette.View.prototype.close.apply(this, arguments);
  384. this.trigger("collection:closed");
  385. },
  386. // Close the child views that this collection view
  387. // is holding on to, if any
  388. closeChildren: function(){
  389. var that = this;
  390. if (this.children){
  391. _.each(_.clone(this.children), function(childView){
  392. that.removeItemView(childView.model);
  393. });
  394. }
  395. }
  396. });
  397. // Composite View
  398. // --------------
  399. // Used for rendering a branch-leaf, hierarchical structure.
  400. // Extends directly from CollectionView and also renders an
  401. // an item view as `modelView`, for the top leaf
  402. Marionette.CompositeView = Marionette.CollectionView.extend({
  403. constructor: function(options){
  404. Marionette.CollectionView.apply(this, arguments);
  405. this.itemView = this.getItemView();
  406. },
  407. // Configured the initial events that the composite view
  408. // binds to. Override this method to prevent the initial
  409. // events, or to add your own initial events.
  410. initialEvents: function(){
  411. if (this.collection){
  412. this.bindTo(this.collection, "add", this.addChildView, this);
  413. this.bindTo(this.collection, "remove", this.removeItemView, this);
  414. this.bindTo(this.collection, "reset", this.renderCollection, this);
  415. }
  416. },
  417. // Retrieve the `itemView` to be used when rendering each of
  418. // the items in the collection. The default is to return
  419. // `this.itemView` or Marionette.CompositeView if no `itemView`
  420. // has been defined
  421. getItemView: function(){
  422. return this.itemView || this.constructor;
  423. },
  424. // Renders the model once, and the collection once. Calling
  425. // this again will tell the model's view to re-render itself
  426. // but the collection will not re-render.
  427. render: function(){
  428. var that = this;
  429. var html = this.renderModel();
  430. this.$el.html(html);
  431. this.trigger("composite:model:rendered");
  432. this.trigger("render");
  433. this.renderCollection();
  434. this.trigger("composite:rendered");
  435. },
  436. // Render the collection for the composite view
  437. renderCollection: function(){
  438. Marionette.CollectionView.prototype.render.apply(this, arguments);
  439. this.trigger("composite:collection:rendered");
  440. },
  441. // Render an individual model, if we have one, as
  442. // part of a composite view (branch / leaf). For example:
  443. // a treeview.
  444. renderModel: function(){
  445. var data = {};
  446. data = this.serializeData();
  447. var template = this.getTemplate();
  448. return Marionette.Renderer.render(template, data);
  449. }
  450. });
  451. // Region
  452. // ------
  453. // Manage the visual regions of your composite application. See
  454. // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
  455. Marionette.Region = function(options){
  456. this.options = options || {};
  457. _.extend(this, options);
  458. if (!this.el){
  459. var err = new Error("An 'el' must be specified");
  460. err.name = "NoElError";
  461. throw err;
  462. }
  463. if (this.initialize){
  464. this.initialize.apply(this, arguments);
  465. }
  466. };
  467. _.extend(Marionette.Region.prototype, Backbone.Events, {
  468. // Displays a backbone view instance inside of the region.
  469. // Handles calling the `render` method for you. Reads content
  470. // directly from the `el` attribute. Also calls an optional
  471. // `onShow` and `close` method on your view, just after showing
  472. // or just before closing the view, respectively.
  473. show: function(view){
  474. var that = this;
  475. this.ensureEl();
  476. this.close();
  477. view.render();
  478. this.open(view);
  479. if (view.onShow) { view.onShow(); }
  480. view.trigger("show");
  481. if (this.onShow) { this.onShow(view); }
  482. this.trigger("view:show", view);
  483. this.currentView = view;
  484. },
  485. ensureEl: function(){
  486. if (!this.$el || this.$el.length === 0){
  487. this.$el = this.getEl(this.el);
  488. }
  489. },
  490. // Override this method to change how the region finds the
  491. // DOM element that it manages. Return a jQuery selector object.
  492. getEl: function(selector){
  493. return $(selector);
  494. },
  495. // Override this method to change how the new view is
  496. // appended to the `$el` that the region is managing
  497. open: function(view){
  498. this.$el.html(view.el);
  499. },
  500. // Close the current view, if there is one. If there is no
  501. // current view, it does nothing and returns immediately.
  502. close: function(){
  503. var view = this.currentView;
  504. if (!view){ return; }
  505. if (view.close) { view.close(); }
  506. this.trigger("view:closed", view);
  507. delete this.currentView;
  508. },
  509. // Attach an existing view to the region. This
  510. // will not call `render` or `onShow` for the new view,
  511. // and will not replace the current HTML for the `el`
  512. // of the region.
  513. attachView: function(view){
  514. this.currentView = view;
  515. }
  516. });
  517. // Copy the `extend` function used by Backbone's classes
  518. Marionette.Region.extend = Backbone.View.extend;
  519. // Copy the features of `BindTo`
  520. _.extend(Marionette.Region.prototype, Marionette.BindTo);
  521. // Layout
  522. // ------
  523. // Used for managing application layouts, nested layouts and
  524. // multiple regions within an application or sub-application.
  525. //
  526. // A specialized view type that renders an area of HTML and then
  527. // attaches `Region` instances to the specified `regions`.
  528. // Used for composite view management and sub-application areas.
  529. Marionette.Layout = Marionette.ItemView.extend({
  530. constructor: function () {
  531. Backbone.Marionette.ItemView.apply(this, arguments);
  532. this.initializeRegions();
  533. },
  534. // Layout's render will use the existing region objects the
  535. // first time it is called. Subsequent calls will close the
  536. // views that the regions are showing and then reset the `el`
  537. // for the regions to the newly rendered DOM elements.
  538. render: function(){
  539. var result = Marionette.ItemView.prototype.render.apply(this, arguments);
  540. // Rewrite this function to handle re-rendering and
  541. // re-initializing the `el` for each region
  542. this.render = function(){
  543. this.closeRegions();
  544. this.reInitializeRegions();
  545. var result = Marionette.ItemView.prototype.render.apply(this, arguments);
  546. return result;
  547. }
  548. return result;
  549. },
  550. // Handle closing regions, and then close the view itself.
  551. close: function () {
  552. this.closeRegions();
  553. this.destroyRegions();
  554. Backbone.Marionette.ItemView.prototype.close.call(this, arguments);
  555. },
  556. // Initialize the regions that have been defined in a
  557. // `regions` attribute on this layout. The key of the
  558. // hash becomes an attribute on the layout object directly.
  559. // For example: `regions: { menu: ".menu-container" }`
  560. // will product a `layout.menu` object which is a region
  561. // that controls the `.menu-container` DOM element.
  562. initializeRegions: function () {
  563. if (!this.regionManagers){
  564. this.regionManagers = {};
  565. }
  566. var that = this;
  567. _.each(this.regions, function (selector, name) {
  568. var regionManager = new Backbone.Marionette.Region({
  569. el: selector,
  570. getEl: function(selector){
  571. return that.$(selector);
  572. }
  573. });
  574. that.regionManagers[name] = regionManager;
  575. that[name] = regionManager;
  576. });
  577. },
  578. // Re-initialize all of the regions by updating the `el` that
  579. // they point to
  580. reInitializeRegions: function(){
  581. _.each(this.regionManagers, function(region){
  582. delete region.$el;
  583. });
  584. },
  585. // Close all of the regions that have been opened by
  586. // this layout. This method is called when the layout
  587. // itself is closed.
  588. closeRegions: function () {
  589. var that = this;
  590. _.each(this.regionManagers, function (manager, name) {
  591. manager.close();
  592. });
  593. },
  594. // Destroys all of the regions by removing references
  595. // from the Layout
  596. destroyRegions: function(){
  597. var that = this;
  598. _.each(this.regionManagers, function (manager, name) {
  599. delete that[name];
  600. });
  601. this.regionManagers = {};
  602. }
  603. });
  604. // Application
  605. // -----------
  606. // Contain and manage the composite application as a whole.
  607. // Stores and starts up `Region` objects, includes an
  608. // event aggregator as `app.vent`
  609. Marionette.Application = function(options){
  610. this.initCallbacks = new Marionette.Callbacks();
  611. this.vent = new Marionette.EventAggregator();
  612. _.extend(this, options);
  613. };
  614. _.extend(Marionette.Application.prototype, Backbone.Events, {
  615. // Add an initializer that is either run at when the `start`
  616. // method is called, or run immediately if added after `start`
  617. // has already been called.
  618. addInitializer: function(initializer){
  619. this.initCallbacks.add(initializer);
  620. },
  621. // kick off all of the application's processes.
  622. // initializes all of the regions that have been added
  623. // to the app, and runs all of the initializer functions
  624. start: function(options){
  625. this.trigger("initialize:before", options);
  626. this.initCallbacks.run(options, this);
  627. this.trigger("initialize:after", options);
  628. this.trigger("start", options);
  629. },
  630. // Add regions to your app.
  631. // Accepts a hash of named strings or Region objects
  632. // addRegions({something: "#someRegion"})
  633. // addRegions{{something: Region.extend({el: "#someRegion"}) });
  634. addRegions: function(regions){
  635. var regionValue, regionObj, region;
  636. for(region in regions){
  637. if (regions.hasOwnProperty(region)){
  638. regionValue = regions[region];
  639. if (typeof regionValue === "string"){
  640. regionObj = new Marionette.Region({
  641. el: regionValue
  642. });
  643. } else {
  644. regionObj = new regionValue();
  645. }
  646. this[region] = regionObj;
  647. }
  648. }
  649. },
  650. // Create a module, attached to the application
  651. module: function(){
  652. // see the Marionette.Module object for more information
  653. return Marionette.Module.create.apply(this, arguments);
  654. }
  655. });
  656. // Copy the `extend` function used by Backbone's classes
  657. Marionette.Application.extend = Backbone.View.extend;
  658. // Copy the features of `BindTo`
  659. _.extend(Marionette.Application.prototype, Marionette.BindTo);
  660. // AppRouter
  661. // ---------
  662. // Reduce the boilerplate code of handling route events
  663. // and then calling a single method on another object.
  664. // Have your routers configured to call the method on
  665. // your object, directly.
  666. //
  667. // Configure an AppRouter with `appRoutes`.
  668. //
  669. // App routers can only take one `controller` object.
  670. // It is recommended that you divide your controller
  671. // objects in to smaller peices of related functionality
  672. // and have multiple routers / controllers, instead of
  673. // just one giant router and controller.
  674. //
  675. // You can also add standard routes to an AppRouter.
  676. Marionette.AppRouter = Backbone.Router.extend({
  677. constructor: function(options){
  678. Backbone.Router.prototype.constructor.call(this, options);
  679. if (this.appRoutes){
  680. var controller = this.controller;
  681. if (options && options.controller) {
  682. controller = options.controller;
  683. }
  684. this.processAppRoutes(controller, this.appRoutes);
  685. }
  686. },
  687. // Internal method to process the `appRoutes` for the
  688. // router, and turn them in to routes that trigger the
  689. // specified method on the specified `controller`.
  690. processAppRoutes: function(controller, appRoutes){
  691. var method, methodName;
  692. var route, routesLength, i;
  693. var routes = [];
  694. var router = this;
  695. for(route in appRoutes){
  696. if (appRoutes.hasOwnProperty(route)){
  697. routes.unshift([route, appRoutes[route]]);
  698. }
  699. }
  700. routesLength = routes.length;
  701. for (i = 0; i < routesLength; i++){
  702. route = routes[i][0];
  703. methodName = routes[i][1];
  704. method = controller[methodName];
  705. if (!method){
  706. var msg = "Method '" + methodName + "' was not found on the controller";
  707. var err = new Error(msg);
  708. err.name = "NoMethodError";
  709. throw err;
  710. }
  711. method = _.bind(method, controller);
  712. router.route(route, methodName, method);
  713. }
  714. }
  715. });
  716. // Module
  717. // ------
  718. // A simple module system, used to create privacy and encapsulation in
  719. // Marionette applications
  720. Marionette.Module = function(){};
  721. // Extend the Module prototype with events / bindTo, so that the module
  722. // can be used as an event aggregator or pub/sub.
  723. _.extend(Marionette.Module.prototype, Backbone.Events, Marionette.BindTo);
  724. // Function level methods to create modules
  725. _.extend(Marionette.Module, {
  726. // Create a module, hanging off 'this' as the parent object. This
  727. // method must be called with .apply or .create
  728. create: function(moduleNames, moduleDefinition){
  729. var moduleName, module, moduleOverride;
  730. var parentObject = this;
  731. var parentModule = this;
  732. var moduleNames = moduleNames.split(".");
  733. // Loop through all the parts of the module definition
  734. var length = moduleNames.length;
  735. for(var i = 0; i < length; i++){
  736. var isLastModuleInChain = (i === length-1);
  737. // Get the module name, and check if it exists on
  738. // the current parent already
  739. moduleName = moduleNames[i];
  740. module = parentModule[moduleName];
  741. // Create a new module if we don't have one already
  742. if (!module){
  743. module = new Marionette.Module();
  744. }
  745. // Check to see if we need to run the definition
  746. // for the module. Only run the definition if one
  747. // is supplied, and if we're at the last segment
  748. // of the "Module.Name" chain.
  749. if (isLastModuleInChain && moduleDefinition){
  750. // get the custom args passed in after the module definition and
  751. // get rid of the module name and definition function
  752. var customArgs = slice.apply(arguments);
  753. customArgs.shift();
  754. customArgs.shift();
  755. // final arguments list for the module definition
  756. var argsArray = [module, parentObject, Backbone, Marionette, jQuery, _, customArgs];
  757. // flatten the nested array
  758. var args = _.flatten(argsArray);
  759. // ensure the module definition's `this` is the module itself
  760. moduleDefinition.apply(module, args);
  761. }
  762. // If the defined module is not what we are
  763. // currently storing as the module, replace it
  764. if (parentModule[moduleName] !== module){
  765. parentModule[moduleName] = module;
  766. }
  767. // Reset the parent module so that the next child
  768. // in the list will be added to the correct parent
  769. parentModule = module;
  770. }
  771. // Return the last module in the definition chain
  772. return module;
  773. }
  774. });
  775. // Template Cache
  776. // --------------
  777. // Manage templates stored in `<script>` blocks,
  778. // caching them for faster access.
  779. Marionette.TemplateCache = function(templateId){
  780. this.templateId = templateId;
  781. };
  782. // TemplateCache object-level methods. Manage the template
  783. // caches from these method calls instead of creating
  784. // your own TemplateCache instances
  785. _.extend(Marionette.TemplateCache, {
  786. templateCaches: {},
  787. // Get the specified template by id. Either
  788. // retrieves the cached version, or loads it
  789. // from the DOM.
  790. get: function(templateId){
  791. var that = this;
  792. var cachedTemplate = this.templateCaches[templateId];
  793. if (!cachedTemplate){
  794. cachedTemplate = new Marionette.TemplateCache(templateId);
  795. this.templateCaches[templateId] = cachedTemplate;
  796. }
  797. return cachedTemplate.load();
  798. },
  799. // Clear templates from the cache. If no arguments
  800. // are specified, clears all templates:
  801. // `clear()`
  802. //
  803. // If arguments are specified, clears each of the
  804. // specified templates from the cache:
  805. // `clear("#t1", "#t2", "...")`
  806. clear: function(){
  807. var i;
  808. var length = arguments.length;
  809. if (length > 0){
  810. for(i=0; i<length; i++){
  811. delete this.templateCaches[arguments[i]];
  812. }
  813. } else {
  814. this.templateCaches = {};
  815. }
  816. }
  817. });
  818. // TemplateCache instance methods, allowing each
  819. // template cache object to manage it's own state
  820. // and know whether or not it has been loaded
  821. _.extend(Marionette.TemplateCache.prototype, {
  822. // Internal method to load the template asynchronously.
  823. load: function(){
  824. var that = this;
  825. // Guard clause to prevent loading this template more than once
  826. if (this.compiledTemplate){
  827. return this.compiledTemplate;
  828. }
  829. // Load the template and compile it
  830. var template = this.loadTemplate(this.templateId);
  831. this.compiledTemplate = this.compileTemplate(template);
  832. return this.compiledTemplate;
  833. },
  834. // Load a template from the DOM, by default. Override
  835. // this method to provide your own template retrieval,
  836. // such as asynchronous loading from a server.
  837. loadTemplate: function(templateId){
  838. var template = $(templateId).html();
  839. if (!template || template.length === 0){
  840. var msg = "Could not find template: '" + templateId + "'";
  841. var err = new Error(msg);
  842. err.name = "NoTemplateError";
  843. throw err;
  844. }
  845. return template;
  846. },
  847. // Pre-compile the template before caching it. Override
  848. // this method if you do not need to pre-compile a template
  849. // (JST / RequireJS for example) or if you want to change
  850. // the template engine used (Handebars, etc).
  851. compileTemplate: function(rawTemplate){
  852. return _.template(rawTemplate);
  853. }
  854. });
  855. // Renderer
  856. // --------
  857. // Render a template with data by passing in the template
  858. // selector and the data to render.
  859. Marionette.Renderer = {
  860. // Render a template with data. The `template` parameter is
  861. // passed to the `TemplateCache` object to retrieve the
  862. // template function. Override this method to provide your own
  863. // custom rendering and template handling for all of Marionette.
  864. render: function(template, data){
  865. var templateFunc = Marionette.TemplateCache.get(template);
  866. var html = templateFunc(data);
  867. return html;
  868. }
  869. };
  870. // Callbacks
  871. // ---------
  872. // A simple way of managing a collection of callbacks
  873. // and executing them at a later point in time, using jQuery's
  874. // `Deferred` object.
  875. Marionette.Callbacks = function(){
  876. this.deferred = $.Deferred();
  877. this.promise = this.deferred.promise();
  878. };
  879. _.extend(Marionette.Callbacks.prototype, {
  880. // Add a callback to be executed. Callbacks added here are
  881. // guaranteed to execute, even if they are added after the
  882. // `run` method is called.
  883. add: function(callback, contextOverride){
  884. this.promise.done(function(context, options){
  885. if (contextOverride){ context = contextOverride; }
  886. callback.call(context, options);
  887. });
  888. },
  889. // Run all registered callbacks with the context specified.
  890. // Additional callbacks can be added after this has been run
  891. // and they will still be executed.
  892. run: function(options, context){
  893. this.deferred.resolve(context, options);
  894. }
  895. });
  896. // Event Aggregator
  897. // ----------------
  898. // A pub-sub object that can be used to decouple various parts
  899. // of an application through event-driven architecture.
  900. Marionette.EventAggregator = function(options){
  901. _.extend(this, options);
  902. };
  903. _.extend(Marionette.EventAggregator.prototype, Backbone.Events, Marionette.BindTo, {
  904. // Assumes the event aggregator itself is the
  905. // object being bound to.
  906. bindTo: function(eventName, callback, context){
  907. return Marionette.BindTo.bindTo.call(this, this, eventName, callback, context);
  908. }
  909. });
  910. // Helpers
  911. // -------
  912. // For slicing `arguments` in functions
  913. var slice = Array.prototype.slice;
  914. return Marionette;
  915. })(Backbone, _, window.jQuery || window.Zepto || window.ender);
  916. return Backbone.Marionette;
  917. }));