PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

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