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

/ajax/libs/backbone.layoutmanager/0.8.4/backbone.layoutmanager.js

https://bitbucket.org/kolbyjAFK/cdnjs
JavaScript | 843 lines | 425 code | 150 blank | 268 comment | 92 complexity | ea328be9423bcc61dfd6d567fb5cc8fb MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. /*!
  2. * backbone.layoutmanager.js v0.8.4
  3. * Copyright 2013, Tim Branyen (@tbranyen)
  4. * backbone.layoutmanager.js may be freely distributed under the MIT license.
  5. */
  6. (function(window) {
  7. "use strict";
  8. // Hoisted, referenced at the bottom of the source. This caches a list of all
  9. // LayoutManager options at definition time.
  10. var keys;
  11. // Localize global dependency references.
  12. var Backbone = window.Backbone;
  13. var _ = window._;
  14. var $ = window.$;
  15. // Maintain references to the two `Backbone.View` functions that are
  16. // overwritten so that they can be proxied.
  17. var _configure = Backbone.View.prototype._configure;
  18. var render = Backbone.View.prototype.render;
  19. // Cache these methods for performance.
  20. var aPush = Array.prototype.push;
  21. var aConcat = Array.prototype.concat;
  22. var aSplice = Array.prototype.splice;
  23. // LayoutManager is a wrapper around a `Backbone.View`.
  24. var LayoutManager = Backbone.View.extend({
  25. // This named function allows for significantly easier debugging.
  26. constructor: function Layout(options) {
  27. // Options may not always be passed to the constructor, this ensures it is
  28. // always an object.
  29. options = options || {};
  30. // Grant this View superpowers.
  31. LayoutManager.setupView(this, options);
  32. // Have Backbone set up the rest of this View.
  33. Backbone.View.call(this, options);
  34. },
  35. // Shorthand to `setView` function with the `insert` flag set.
  36. insertView: function(selector, view) {
  37. // If the `view` argument exists, then a selector was passed in. This code
  38. // path will forward the selector on to `setView`.
  39. if (view) {
  40. return this.setView(selector, view, true);
  41. }
  42. // If no `view` argument is defined, then assume the first argument is the
  43. // View, somewhat now confusingly named `selector`.
  44. return this.setView(selector, true);
  45. },
  46. // Iterate over an object and ensure every value is wrapped in an array to
  47. // ensure they will be inserted, then pass that object to `setViews`.
  48. insertViews: function(views) {
  49. // If an array of views was passed it should be inserted into the
  50. // root view. Much like calling insertView without a selector.
  51. if (_.isArray(views)) {
  52. return this.setViews({ "": views });
  53. }
  54. _.each(views, function(view, selector) {
  55. views[selector] = _.isArray(view) ? view : [view];
  56. });
  57. return this.setViews(views);
  58. },
  59. // Returns the View that matches the `getViews` filter function.
  60. getView: function(fn) {
  61. // If `getView` is invoked with undefined as the first argument, then the
  62. // second argument will be used instead. This is to allow
  63. // `getViews(undefined, fn)` to work as `getViews(fn)`. Useful for when
  64. // you are allowing an optional selector.
  65. if (typeof fn !== "function" && typeof fn !== "string") {
  66. fn = arguments[1];
  67. }
  68. return this.getViews(fn).first().value();
  69. },
  70. // Provide a filter function to get a flattened array of all the subviews.
  71. // If the filter function is omitted it will return all subviews. If a
  72. // String is passed instead, it will return the Views for that selector.
  73. getViews: function(fn) {
  74. // Generate an array of all top level (no deeply nested) Views flattened.
  75. var views = _.chain(this.views).map(function(view) {
  76. return _.isArray(view) ? view : [view];
  77. }, this).flatten().value();
  78. // If the filter argument is a String, then return a chained Version of the
  79. // elements.
  80. if (typeof fn === "string") {
  81. return _.chain([this.views[fn]]).flatten();
  82. }
  83. // If the argument passed is an Object, then pass it to `_.where`.
  84. if (typeof fn === "object") {
  85. return _.chain([_.where(views, fn)]).flatten();
  86. }
  87. // If a filter function is provided, run it on all Views and return a
  88. // wrapped chain. Otherwise, simply return a wrapped chain of all Views.
  89. return _.chain(typeof fn === "function" ? _.filter(views, fn) : views);
  90. },
  91. // Use this to remove Views, internally uses `getViews` so you can pass the
  92. // same argument here as you would to that method.
  93. removeView: function(fn) {
  94. // Allow an optional selector or function to find the right model and
  95. // remove nested Views based off the results of the selector or filter.
  96. return this.getViews(fn).each(function(nestedView) {
  97. nestedView.remove();
  98. });
  99. },
  100. // This takes in a partial name and view instance and assigns them to
  101. // the internal collection of views. If a view is not a LayoutManager
  102. // instance, then mix in the LayoutManager prototype. This ensures
  103. // all Views can be used successfully.
  104. //
  105. // Must definitely wrap any render method passed in or defaults to a
  106. // typical render function `return layout(this).render()`.
  107. setView: function(name, view, insert) {
  108. var manager, existing, options;
  109. // Parent view, the one you are setting a View on.
  110. var root = this;
  111. // If no name was passed, use an empty string and shift all arguments.
  112. if (typeof name !== "string") {
  113. insert = view;
  114. view = name;
  115. name = "";
  116. }
  117. // If the parent views object doesn't exist... create it.
  118. this.views = this.views || {};
  119. // Shorthand the `__manager__` property.
  120. manager = view.__manager__;
  121. // Shorthand the View that potentially already exists.
  122. existing = this.views[name];
  123. // If the View has not been properly set up, throw an Error message
  124. // indicating that the View needs `manage: true` set.
  125. if (!manager) {
  126. throw new Error("Please set `View#manage` property with selector '" +
  127. name + "' to `true`.");
  128. }
  129. // Assign options.
  130. options = view.getAllOptions();
  131. // Add reference to the parentView.
  132. manager.parent = root;
  133. // Add reference to the placement selector used.
  134. manager.selector = name;
  135. // Set up event bubbling, inspired by Backbone.ViewMaster. Do not bubble
  136. // internal events that are triggered.
  137. view.on("all", function(name) {
  138. if (name !== "beforeRender" && name !== "afterRender") {
  139. root.trigger.apply(root, arguments);
  140. }
  141. }, view);
  142. // Code path is less complex for Views that are not being inserted. Simply
  143. // remove existing Views and bail out with the assignment.
  144. if (!insert) {
  145. // If the View we are adding has already been rendered, simply inject it
  146. // into the parent.
  147. if (manager.hasRendered) {
  148. // Apply the partial.
  149. options.partial(root.$el, view.$el, root.__manager__, manager);
  150. }
  151. // Ensure remove is called when swapping View's.
  152. if (existing) {
  153. // If the views are an array, iterate and remove each individually.
  154. _.each(aConcat.call([], existing), function(nestedView) {
  155. nestedView.remove();
  156. });
  157. }
  158. // Assign to main views object and return for chainability.
  159. return this.views[name] = view;
  160. }
  161. // Ensure this.views[name] is an array and push this View to the end.
  162. this.views[name] = aConcat.call([], existing || [], view);
  163. // Put the view into `insert` mode.
  164. manager.insert = true;
  165. return view;
  166. },
  167. // Allows the setting of multiple views instead of a single view.
  168. setViews: function(views) {
  169. // Iterate over all the views and use the View's view method to assign.
  170. _.each(views, function(view, name) {
  171. // If the view is an array put all views into insert mode.
  172. if (_.isArray(view)) {
  173. return _.each(view, function(view) {
  174. this.insertView(name, view);
  175. }, this);
  176. }
  177. // Assign each view using the view function.
  178. this.setView(name, view);
  179. }, this);
  180. // Allow for chaining
  181. return this;
  182. },
  183. // By default this should find all nested views and render them into
  184. // the this.el and call done once all of them have successfully been
  185. // resolved.
  186. //
  187. // This function returns a promise that can be chained to determine
  188. // once all subviews and main view have been rendered into the view.el.
  189. render: function() {
  190. var root = this;
  191. var options = root.getAllOptions();
  192. var manager = root.__manager__;
  193. var parent = manager.parent;
  194. var rentManager = parent && parent.__manager__;
  195. var def = options.deferred();
  196. // Triggered once the render has succeeded.
  197. function resolve() {
  198. var next, afterRender;
  199. // If there is a parent, attach.
  200. if (parent) {
  201. if (!options.contains(parent.el, root.el)) {
  202. // Apply the partial.
  203. options.partial(parent.$el, root.$el, rentManager, manager);
  204. }
  205. }
  206. // Ensure events are always correctly bound after rendering.
  207. root.delegateEvents();
  208. // Set this View as successfully rendered.
  209. manager.hasRendered = true;
  210. // Only process the queue if it exists.
  211. if (next = manager.queue.shift()) {
  212. // Ensure that the next render is only called after all other
  213. // `done` handlers have completed. This will prevent `render`
  214. // callbacks from firing out of order.
  215. next();
  216. } else {
  217. // Once the queue is depleted, remove it, the render process has
  218. // completed.
  219. delete manager.queue;
  220. }
  221. // Reusable function for triggering the afterRender callback and event
  222. // and setting the hasRendered flag.
  223. function completeRender() {
  224. var afterRender = options.afterRender;
  225. if (afterRender) {
  226. afterRender.call(root, root);
  227. }
  228. // Always emit an afterRender event.
  229. root.trigger("afterRender", root);
  230. }
  231. // If the parent is currently rendering, wait until it has completed
  232. // until calling the nested View's `afterRender`.
  233. if (rentManager && rentManager.queue) {
  234. // Wait until the parent View has finished rendering, which could be
  235. // asynchronous, and trigger afterRender on this View once it has
  236. // compeleted.
  237. parent.once("afterRender", completeRender);
  238. } else {
  239. // This View and its parent have both rendered.
  240. completeRender();
  241. }
  242. return def.resolveWith(root, [root]);
  243. }
  244. // Actually facilitate a render.
  245. function actuallyRender() {
  246. var options = root.getAllOptions();
  247. var manager = root.__manager__;
  248. var parent = manager.parent;
  249. var rentManager = parent && parent.__manager__;
  250. // The `_viewRender` method is broken out to abstract away from having
  251. // too much code in `actuallyRender`.
  252. root._render(LayoutManager._viewRender, options).done(function() {
  253. // If there are no children to worry about, complete the render
  254. // instantly.
  255. if (!_.keys(root.views).length) {
  256. return resolve();
  257. }
  258. // Create a list of promises to wait on until rendering is done.
  259. // Since this method will run on all children as well, its sufficient
  260. // for a full hierarchical.
  261. var promises = _.map(root.views, function(view) {
  262. var insert = _.isArray(view);
  263. // If items are being inserted, they will be in a non-zero length
  264. // Array.
  265. if (insert && view.length) {
  266. // Schedule each view to be rendered in order and return a promise
  267. // representing the result of the final rendering.
  268. return _.reduce(view.slice(1), function(prevRender, view) {
  269. return prevRender.then(function() {
  270. return view.render();
  271. });
  272. // The first view should be rendered immediately, and the resulting
  273. // promise used to initialize the reduction.
  274. }, view[0].render());
  275. }
  276. // Only return the fetch deferred, resolve the main deferred after
  277. // the element has been attached to it's parent.
  278. return !insert ? view.render() : view;
  279. });
  280. // Once all nested Views have been rendered, resolve this View's
  281. // deferred.
  282. options.when(promises).done(resolve);
  283. });
  284. }
  285. // Another render is currently happening if there is an existing queue, so
  286. // push a closure to render later into the queue.
  287. if (manager.queue) {
  288. aPush.call(manager.queue, actuallyRender);
  289. } else {
  290. manager.queue = [];
  291. // This the first `render`, preceeding the `queue` so render
  292. // immediately.
  293. actuallyRender(root, def);
  294. }
  295. // Add the View to the deferred so that `view.render().view.el` is
  296. // possible.
  297. def.view = root;
  298. // This is the promise that determines if the `render` function has
  299. // completed or not.
  300. return def;
  301. },
  302. // Ensure the cleanup function is called whenever remove is called.
  303. remove: function() {
  304. // Force remove itself from its parent.
  305. LayoutManager._removeView(this, true);
  306. // Call the original remove function.
  307. return this._remove.apply(this, arguments);
  308. },
  309. // Merge instance and global options.
  310. getAllOptions: function() {
  311. // Instance overrides take precedence, fallback to prototype options.
  312. return _.extend({}, this, LayoutManager.prototype.options, this.options);
  313. }
  314. },
  315. {
  316. // Clearable cache.
  317. _cache: {},
  318. // Creates a deferred and returns a function to call when finished.
  319. _makeAsync: function(options, done) {
  320. var handler = options.deferred();
  321. // Used to handle asynchronous renders.
  322. handler.async = function() {
  323. handler._isAsync = true;
  324. return done;
  325. };
  326. return handler;
  327. },
  328. // This gets passed to all _render methods. The `root` value here is passed
  329. // from the `manage(this).render()` line in the `_render` function
  330. _viewRender: function(root, options) {
  331. var url, contents, fetchAsync, renderedEl;
  332. var manager = root.__manager__;
  333. // This function is responsible for pairing the rendered template into
  334. // the DOM element.
  335. function applyTemplate(rendered) {
  336. // Actually put the rendered contents into the element.
  337. if (rendered) {
  338. // If no container is specified, we must replace the content.
  339. if (manager.noel) {
  340. // Hold a reference to created element as replaceWith doesn't return new el.
  341. renderedEl = root.$el.html(rendered).children();
  342. root.$el.replaceWith(renderedEl);
  343. // Don't delegate events here - we'll do that in resolve()
  344. root.setElement(renderedEl, false);
  345. } else {
  346. options.html(root.$el, rendered);
  347. }
  348. }
  349. // Resolve only after fetch and render have succeeded.
  350. fetchAsync.resolveWith(root, [root]);
  351. }
  352. // Once the template is successfully fetched, use its contents to proceed.
  353. // Context argument is first, since it is bound for partial application
  354. // reasons.
  355. function done(context, contents) {
  356. // Store the rendered template someplace so it can be re-assignable.
  357. var rendered;
  358. // This allows the `render` method to be asynchronous as well as `fetch`.
  359. var renderAsync = LayoutManager._makeAsync(options, function(rendered) {
  360. applyTemplate(rendered);
  361. });
  362. // Ensure the cache is up-to-date.
  363. LayoutManager.cache(url, contents);
  364. // Render the View into the el property.
  365. if (contents) {
  366. rendered = options.render.call(renderAsync, contents, context);
  367. }
  368. // If the function was synchronous, continue execution.
  369. if (!renderAsync._isAsync) {
  370. applyTemplate(rendered);
  371. }
  372. }
  373. return {
  374. // This `render` function is what gets called inside of the View render,
  375. // when `manage(this).render` is called. Returns a promise that can be
  376. // used to know when the element has been rendered into its parent.
  377. render: function() {
  378. var context = root.serialize || options.serialize;
  379. var template = root.template || options.template;
  380. // If data is a function, immediately call it.
  381. if (_.isFunction(context)) {
  382. context = context.call(root);
  383. }
  384. // This allows for `var done = this.async()` and then `done(contents)`.
  385. fetchAsync = LayoutManager._makeAsync(options, function(contents) {
  386. done(context, contents);
  387. });
  388. // Set the url to the prefix + the view's template property.
  389. if (typeof template === "string") {
  390. url = options.prefix + template;
  391. }
  392. // Check if contents are already cached and if they are, simply process
  393. // the template with the correct data.
  394. if (contents = LayoutManager.cache(url)) {
  395. done(context, contents, url);
  396. return fetchAsync;
  397. }
  398. // Fetch layout and template contents.
  399. if (typeof template === "string") {
  400. contents = options.fetch.call(fetchAsync, options.prefix + template);
  401. // If the template is already a function, simply call it.
  402. } else if (typeof template === "function") {
  403. contents = template;
  404. // If its not a string and not undefined, pass the value to `fetch`.
  405. } else if (template != null) {
  406. contents = options.fetch.call(fetchAsync, template);
  407. }
  408. // If the function was synchronous, continue execution.
  409. if (!fetchAsync._isAsync) {
  410. done(context, contents);
  411. }
  412. return fetchAsync;
  413. }
  414. };
  415. },
  416. // Remove all nested Views.
  417. _removeViews: function(root, force) {
  418. var views;
  419. // Shift arguments around.
  420. if (typeof root === "boolean") {
  421. force = root;
  422. root = this;
  423. }
  424. // Allow removeView to be called on instances.
  425. root = root || this;
  426. // Iterate over all of the nested View's and remove.
  427. root.getViews().each(function(view) {
  428. // Force doesn't care about if a View has rendered or not.
  429. if (view.__manager__.hasRendered || force) {
  430. LayoutManager._removeView(view, force);
  431. }
  432. });
  433. },
  434. // Remove a single nested View.
  435. _removeView: function(view, force) {
  436. var parentViews;
  437. // Shorthand the manager for easier access.
  438. var manager = view.__manager__;
  439. // Test for keep.
  440. var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
  441. // Only remove views that do not have `keep` attribute set, unless the
  442. // View is in `insert` mode and the force flag is set.
  443. if (!keep && (manager.insert === true || force)) {
  444. // Clean out the events.
  445. LayoutManager.cleanViews(view);
  446. // Since we are removing this view, force subviews to remove
  447. view._removeViews(true);
  448. // Remove the View completely.
  449. view.$el.remove();
  450. // Bail out early if no parent exists.
  451. if (!manager.parent) { return; }
  452. // Assign (if they exist) the sibling Views to a property.
  453. parentViews = manager.parent.views[manager.selector];
  454. // If this is an array of items remove items that are not marked to
  455. // keep.
  456. if (_.isArray(parentViews)) {
  457. // Remove duplicate Views.
  458. return _.each(_.clone(parentViews), function(view, i) {
  459. // If the managers match, splice off this View.
  460. if (view && view.__manager__ === manager) {
  461. aSplice.call(parentViews, i, 1);
  462. }
  463. });
  464. }
  465. // Otherwise delete the parent selector.
  466. delete manager.parent.views[manager.selector];
  467. }
  468. },
  469. // Cache templates into LayoutManager._cache.
  470. cache: function(path, contents) {
  471. // If template path is found in the cache, return the contents.
  472. if (path in this._cache && contents == null) {
  473. return this._cache[path];
  474. // Ensure path and contents aren't undefined.
  475. } else if (path != null && contents != null) {
  476. return this._cache[path] = contents;
  477. }
  478. // If the template is not in the cache, return undefined.
  479. },
  480. // Accept either a single view or an array of views to clean of all DOM
  481. // events internal model and collection references and all Backbone.Events.
  482. cleanViews: function(views) {
  483. // Clear out all existing views.
  484. _.each(aConcat.call([], views), function(view) {
  485. // Remove all custom events attached to this View.
  486. view.unbind();
  487. // Automatically unbind `model`.
  488. if (view.model instanceof Backbone.Model) {
  489. view.model.off(null, null, view);
  490. }
  491. // Automatically unbind `collection`.
  492. if (view.collection instanceof Backbone.Collection) {
  493. view.collection.off(null, null, view);
  494. }
  495. // Automatically unbind events bound to this View.
  496. view.stopListening();
  497. // If a custom cleanup method was provided on the view, call it after
  498. // the initial cleanup is done
  499. _.result(view, "cleanup");
  500. });
  501. },
  502. // This static method allows for global configuration of LayoutManager.
  503. configure: function(options) {
  504. _.extend(LayoutManager.prototype.options, options);
  505. // Allow LayoutManager to manage Backbone.View.prototype.
  506. if (options.manage) {
  507. Backbone.View.prototype.manage = true;
  508. }
  509. // Disable the element globally.
  510. if (options.el === false) {
  511. Backbone.View.prototype.el = false;
  512. }
  513. },
  514. // Configure a View to work with the LayoutManager plugin.
  515. setupView: function(views, options) {
  516. // Set up all Views passed.
  517. _.each(aConcat.call([], views), function(view) {
  518. // If the View has already been setup, no need to do it again.
  519. if (view.__manager__) {
  520. return;
  521. }
  522. var views, declaredViews, viewOptions;
  523. var proto = LayoutManager.prototype;
  524. var viewOverrides = _.pick(view, keys);
  525. // Ensure necessary properties are set.
  526. _.defaults(view, {
  527. // Ensure a view always has a views object.
  528. views: {},
  529. // Internal state object used to store whether or not a View has been
  530. // taken over by layout manager and if it has been rendered into the DOM.
  531. __manager__: {},
  532. // Add the ability to remove all Views.
  533. _removeViews: LayoutManager._removeViews,
  534. // Add the ability to remove itself.
  535. _removeView: LayoutManager._removeView
  536. // Mix in all LayoutManager prototype properties as well.
  537. }, LayoutManager.prototype);
  538. // Extend the options with the prototype and passed options.
  539. options = view.options = _.defaults(options || {}, view.options,
  540. proto.options);
  541. // Ensure view events are properly copied over.
  542. viewOptions = _.pick(options, aConcat.call(["events"],
  543. _.values(options.events)));
  544. // Merge the View options into the View.
  545. _.extend(view, viewOptions);
  546. // If the View still has the Backbone.View#render method, remove it. Don't
  547. // want it accidentally overriding the LM render.
  548. if (viewOverrides.render === LayoutManager.prototype.render ||
  549. viewOverrides.render === Backbone.View.prototype.render) {
  550. delete viewOverrides.render;
  551. }
  552. // Pick out the specific properties that can be dynamically added at
  553. // runtime and ensure they are available on the view object.
  554. _.extend(options, viewOverrides);
  555. // By default the original Remove function is the Backbone.View one.
  556. view._remove = Backbone.View.prototype.remove;
  557. // Always use this render function when using LayoutManager.
  558. view._render = function(manage, options) {
  559. // Keep the view consistent between callbacks and deferreds.
  560. var view = this;
  561. // Shorthand the manager.
  562. var manager = view.__manager__;
  563. // Cache these properties.
  564. var beforeRender = options.beforeRender;
  565. // Ensure all nested Views are properly scrubbed if re-rendering.
  566. if (manager.hasRendered) {
  567. this._removeViews();
  568. }
  569. // If a beforeRender function is defined, call it.
  570. if (beforeRender) {
  571. beforeRender.call(this, this);
  572. }
  573. // Always emit a beforeRender event.
  574. this.trigger("beforeRender", this);
  575. // Render!
  576. return manage(this, options).render();
  577. };
  578. // Ensure the render is always set correctly.
  579. view.render = LayoutManager.prototype.render;
  580. // If the user provided their own remove override, use that instead of the
  581. // default.
  582. if (view.remove !== proto.remove) {
  583. view._remove = view.remove;
  584. view.remove = proto.remove;
  585. }
  586. // Normalize views to exist on either instance or options, default to
  587. // options.
  588. views = options.views || view.views;
  589. // Set the internal views, only if selectors have been provided.
  590. if (_.keys(views).length) {
  591. // Keep original object declared containing Views.
  592. declaredViews = views;
  593. // Reset the property to avoid duplication or overwritting.
  594. view.views = {};
  595. // Set the declared Views.
  596. view.setViews(declaredViews);
  597. }
  598. // If a template is passed use that instead.
  599. if (view.options.template) {
  600. view.options.template = options.template;
  601. // Ensure the template is mapped over.
  602. } else if (view.template) {
  603. options.template = view.template;
  604. // Remove it from the instance.
  605. delete view.template;
  606. }
  607. });
  608. }
  609. });
  610. // Convenience assignment to make creating Layout's slightly shorter.
  611. Backbone.Layout = LayoutManager;
  612. // Tack on the version.
  613. LayoutManager.VERSION = "0.8.4";
  614. // Override _configure to provide extra functionality that is necessary in
  615. // order for the render function reference to be bound during initialize.
  616. Backbone.View.prototype._configure = function(options) {
  617. var noel, retVal;
  618. // Remove the container element provided by Backbone.
  619. if ("el" in options ? options.el === false : this.el === false) {
  620. noel = true;
  621. }
  622. // Run the original _configure.
  623. retVal = _configure.apply(this, arguments);
  624. // If manage is set, do it!
  625. if (options.manage || this.manage) {
  626. // Set up this View.
  627. LayoutManager.setupView(this);
  628. }
  629. // Assign the `noel` property once we're sure the View we're working with is
  630. // mangaed by LayoutManager.
  631. if (this.__manager__) {
  632. this.__manager__.noel = noel;
  633. }
  634. // Act like nothing happened.
  635. return retVal;
  636. };
  637. // Default configuration options; designed to be overriden.
  638. LayoutManager.prototype.options = {
  639. // Prefix template/layout paths.
  640. prefix: "",
  641. // Can be used to supply a different deferred implementation.
  642. deferred: function() {
  643. return $.Deferred();
  644. },
  645. // Fetch is passed a path and is expected to return template contents as a
  646. // function or string.
  647. fetch: function(path) {
  648. return _.template($(path).html());
  649. },
  650. // This is the most common way you will want to partially apply a view into
  651. // a layout.
  652. partial: function($root, $el, rentManager, manager) {
  653. // If selector is specified, attempt to find it.
  654. if (manager.selector) {
  655. if (rentManager.noel) {
  656. var $filtered = $root.filter(manager.selector);
  657. $root = $filtered.length ? $filtered : $root.find(manager.selector);
  658. } else {
  659. $root = $root.find(manager.selector);
  660. }
  661. }
  662. // Use the insert method if insert argument is true.
  663. if (manager.insert) {
  664. this.insert($root, $el);
  665. } else {
  666. this.html($root, $el);
  667. }
  668. },
  669. // Override this with a custom HTML method, passed a root element and content
  670. // (a jQuery collection or a string) to replace the innerHTML with.
  671. html: function($root, content) {
  672. $root.html(content);
  673. },
  674. // Very similar to HTML except this one will appendChild by default.
  675. insert: function($root, $el) {
  676. $root.append($el);
  677. },
  678. // Return a deferred for when all promises resolve/reject.
  679. when: function(promises) {
  680. return $.when.apply(null, promises);
  681. },
  682. // By default, render using underscore's templating.
  683. render: function(template, context) {
  684. return template(context);
  685. },
  686. // A method to determine if a View contains another.
  687. contains: function(parent, child) {
  688. return $.contains(parent, child);
  689. }
  690. };
  691. // Maintain a list of the keys at define time.
  692. keys = _.keys(LayoutManager.prototype.options);
  693. })(typeof global === "object" ? global : this);