PageRenderTime 27ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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