PageRenderTime 29ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/backbone.marionette/0.9.1-bundled/backbone.marionette.js

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