PageRenderTime 32ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 1ms

/ajax/libs/backbone.marionette/0.9.2/backbone.marionette.js

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