backbone.marionette.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  1. // MarionetteJS (Backbone.Marionette)
  2. // ----------------------------------
  3. // v1.2.2
  4. //
  5. // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
  6. // Distributed under MIT license
  7. //
  8. // http://marionettejs.com
  9. /*!
  10. * Includes BabySitter
  11. * https://github.com/marionettejs/backbone.babysitter/
  12. *
  13. * Includes Wreqr
  14. * https://github.com/marionettejs/backbone.wreqr/
  15. */
  16. // Backbone.BabySitter
  17. // -------------------
  18. // v0.0.6
  19. //
  20. // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
  21. // Distributed under MIT license
  22. //
  23. // http://github.com/babysitterjs/backbone.babysitter
  24. // Backbone.ChildViewContainer
  25. // ---------------------------
  26. //
  27. // Provide a container to store, retrieve and
  28. // shut down child views.
  29. Backbone.ChildViewContainer = (function(Backbone, _){
  30. // Container Constructor
  31. // ---------------------
  32. var Container = function(views){
  33. this._views = {};
  34. this._indexByModel = {};
  35. this._indexByCustom = {};
  36. this._updateLength();
  37. _.each(views, this.add, this);
  38. };
  39. // Container Methods
  40. // -----------------
  41. _.extend(Container.prototype, {
  42. // Add a view to this container. Stores the view
  43. // by `cid` and makes it searchable by the model
  44. // cid (and model itself). Optionally specify
  45. // a custom key to store an retrieve the view.
  46. add: function(view, customIndex){
  47. var viewCid = view.cid;
  48. // store the view
  49. this._views[viewCid] = view;
  50. // index it by model
  51. if (view.model){
  52. this._indexByModel[view.model.cid] = viewCid;
  53. }
  54. // index by custom
  55. if (customIndex){
  56. this._indexByCustom[customIndex] = viewCid;
  57. }
  58. this._updateLength();
  59. },
  60. // Find a view by the model that was attached to
  61. // it. Uses the model's `cid` to find it.
  62. findByModel: function(model){
  63. return this.findByModelCid(model.cid);
  64. },
  65. // Find a view by the `cid` of the model that was attached to
  66. // it. Uses the model's `cid` to find the view `cid` and
  67. // retrieve the view using it.
  68. findByModelCid: function(modelCid){
  69. var viewCid = this._indexByModel[modelCid];
  70. return this.findByCid(viewCid);
  71. },
  72. // Find a view by a custom indexer.
  73. findByCustom: function(index){
  74. var viewCid = this._indexByCustom[index];
  75. return this.findByCid(viewCid);
  76. },
  77. // Find by index. This is not guaranteed to be a
  78. // stable index.
  79. findByIndex: function(index){
  80. return _.values(this._views)[index];
  81. },
  82. // retrieve a view by it's `cid` directly
  83. findByCid: function(cid){
  84. return this._views[cid];
  85. },
  86. // Remove a view
  87. remove: function(view){
  88. var viewCid = view.cid;
  89. // delete model index
  90. if (view.model){
  91. delete this._indexByModel[view.model.cid];
  92. }
  93. // delete custom index
  94. _.any(this._indexByCustom, function(cid, key) {
  95. if (cid === viewCid) {
  96. delete this._indexByCustom[key];
  97. return true;
  98. }
  99. }, this);
  100. // remove the view from the container
  101. delete this._views[viewCid];
  102. // update the length
  103. this._updateLength();
  104. },
  105. // Call a method on every view in the container,
  106. // passing parameters to the call method one at a
  107. // time, like `function.call`.
  108. call: function(method){
  109. this.apply(method, _.tail(arguments));
  110. },
  111. // Apply a method on every view in the container,
  112. // passing parameters to the call method one at a
  113. // time, like `function.apply`.
  114. apply: function(method, args){
  115. _.each(this._views, function(view){
  116. if (_.isFunction(view[method])){
  117. view[method].apply(view, args || []);
  118. }
  119. });
  120. },
  121. // Update the `.length` attribute on this container
  122. _updateLength: function(){
  123. this.length = _.size(this._views);
  124. }
  125. });
  126. // Borrowing this code from Backbone.Collection:
  127. // http://backbonejs.org/docs/backbone.html#section-106
  128. //
  129. // Mix in methods from Underscore, for iteration, and other
  130. // collection related features.
  131. var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
  132. 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
  133. 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
  134. 'last', 'without', 'isEmpty', 'pluck'];
  135. _.each(methods, function(method) {
  136. Container.prototype[method] = function() {
  137. var views = _.values(this._views);
  138. var args = [views].concat(_.toArray(arguments));
  139. return _[method].apply(_, args);
  140. };
  141. });
  142. // return the public API
  143. return Container;
  144. })(Backbone, _);
  145. // Backbone.Wreqr (Backbone.Marionette)
  146. // ----------------------------------
  147. // v0.2.0
  148. //
  149. // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
  150. // Distributed under MIT license
  151. //
  152. // http://github.com/marionettejs/backbone.wreqr
  153. Backbone.Wreqr = (function(Backbone, Marionette, _){
  154. "use strict";
  155. var Wreqr = {};
  156. // Handlers
  157. // --------
  158. // A registry of functions to call, given a name
  159. Wreqr.Handlers = (function(Backbone, _){
  160. "use strict";
  161. // Constructor
  162. // -----------
  163. var Handlers = function(options){
  164. this.options = options;
  165. this._wreqrHandlers = {};
  166. if (_.isFunction(this.initialize)){
  167. this.initialize(options);
  168. }
  169. };
  170. Handlers.extend = Backbone.Model.extend;
  171. // Instance Members
  172. // ----------------
  173. _.extend(Handlers.prototype, Backbone.Events, {
  174. // Add multiple handlers using an object literal configuration
  175. setHandlers: function(handlers){
  176. _.each(handlers, function(handler, name){
  177. var context = null;
  178. if (_.isObject(handler) && !_.isFunction(handler)){
  179. context = handler.context;
  180. handler = handler.callback;
  181. }
  182. this.setHandler(name, handler, context);
  183. }, this);
  184. },
  185. // Add a handler for the given name, with an
  186. // optional context to run the handler within
  187. setHandler: function(name, handler, context){
  188. var config = {
  189. callback: handler,
  190. context: context
  191. };
  192. this._wreqrHandlers[name] = config;
  193. this.trigger("handler:add", name, handler, context);
  194. },
  195. // Determine whether or not a handler is registered
  196. hasHandler: function(name){
  197. return !! this._wreqrHandlers[name];
  198. },
  199. // Get the currently registered handler for
  200. // the specified name. Throws an exception if
  201. // no handler is found.
  202. getHandler: function(name){
  203. var config = this._wreqrHandlers[name];
  204. if (!config){
  205. throw new Error("Handler not found for '" + name + "'");
  206. }
  207. return function(){
  208. var args = Array.prototype.slice.apply(arguments);
  209. return config.callback.apply(config.context, args);
  210. };
  211. },
  212. // Remove a handler for the specified name
  213. removeHandler: function(name){
  214. delete this._wreqrHandlers[name];
  215. },
  216. // Remove all handlers from this registry
  217. removeAllHandlers: function(){
  218. this._wreqrHandlers = {};
  219. }
  220. });
  221. return Handlers;
  222. })(Backbone, _);
  223. // Wreqr.CommandStorage
  224. // --------------------
  225. //
  226. // Store and retrieve commands for execution.
  227. Wreqr.CommandStorage = (function(){
  228. "use strict";
  229. // Constructor function
  230. var CommandStorage = function(options){
  231. this.options = options;
  232. this._commands = {};
  233. if (_.isFunction(this.initialize)){
  234. this.initialize(options);
  235. }
  236. };
  237. // Instance methods
  238. _.extend(CommandStorage.prototype, Backbone.Events, {
  239. // Get an object literal by command name, that contains
  240. // the `commandName` and the `instances` of all commands
  241. // represented as an array of arguments to process
  242. getCommands: function(commandName){
  243. var commands = this._commands[commandName];
  244. // we don't have it, so add it
  245. if (!commands){
  246. // build the configuration
  247. commands = {
  248. command: commandName,
  249. instances: []
  250. };
  251. // store it
  252. this._commands[commandName] = commands;
  253. }
  254. return commands;
  255. },
  256. // Add a command by name, to the storage and store the
  257. // args for the command
  258. addCommand: function(commandName, args){
  259. var command = this.getCommands(commandName);
  260. command.instances.push(args);
  261. },
  262. // Clear all commands for the given `commandName`
  263. clearCommands: function(commandName){
  264. var command = this.getCommands(commandName);
  265. command.instances = [];
  266. }
  267. });
  268. return CommandStorage;
  269. })();
  270. // Wreqr.Commands
  271. // --------------
  272. //
  273. // A simple command pattern implementation. Register a command
  274. // handler and execute it.
  275. Wreqr.Commands = (function(Wreqr){
  276. "use strict";
  277. return Wreqr.Handlers.extend({
  278. // default storage type
  279. storageType: Wreqr.CommandStorage,
  280. constructor: function(options){
  281. this.options = options || {};
  282. this._initializeStorage(this.options);
  283. this.on("handler:add", this._executeCommands, this);
  284. var args = Array.prototype.slice.call(arguments);
  285. Wreqr.Handlers.prototype.constructor.apply(this, args);
  286. },
  287. // Execute a named command with the supplied args
  288. execute: function(name, args){
  289. name = arguments[0];
  290. args = Array.prototype.slice.call(arguments, 1);
  291. if (this.hasHandler(name)){
  292. this.getHandler(name).apply(this, args);
  293. } else {
  294. this.storage.addCommand(name, args);
  295. }
  296. },
  297. // Internal method to handle bulk execution of stored commands
  298. _executeCommands: function(name, handler, context){
  299. var command = this.storage.getCommands(name);
  300. // loop through and execute all the stored command instances
  301. _.each(command.instances, function(args){
  302. handler.apply(context, args);
  303. });
  304. this.storage.clearCommands(name);
  305. },
  306. // Internal method to initialize storage either from the type's
  307. // `storageType` or the instance `options.storageType`.
  308. _initializeStorage: function(options){
  309. var storage;
  310. var StorageType = options.storageType || this.storageType;
  311. if (_.isFunction(StorageType)){
  312. storage = new StorageType();
  313. } else {
  314. storage = StorageType;
  315. }
  316. this.storage = storage;
  317. }
  318. });
  319. })(Wreqr);
  320. // Wreqr.RequestResponse
  321. // ---------------------
  322. //
  323. // A simple request/response implementation. Register a
  324. // request handler, and return a response from it
  325. Wreqr.RequestResponse = (function(Wreqr){
  326. "use strict";
  327. return Wreqr.Handlers.extend({
  328. request: function(){
  329. var name = arguments[0];
  330. var args = Array.prototype.slice.call(arguments, 1);
  331. return this.getHandler(name).apply(this, args);
  332. }
  333. });
  334. })(Wreqr);
  335. // Event Aggregator
  336. // ----------------
  337. // A pub-sub object that can be used to decouple various parts
  338. // of an application through event-driven architecture.
  339. Wreqr.EventAggregator = (function(Backbone, _){
  340. "use strict";
  341. var EA = function(){};
  342. // Copy the `extend` function used by Backbone's classes
  343. EA.extend = Backbone.Model.extend;
  344. // Copy the basic Backbone.Events on to the event aggregator
  345. _.extend(EA.prototype, Backbone.Events);
  346. return EA;
  347. })(Backbone, _);
  348. return Wreqr;
  349. })(Backbone, Backbone.Marionette, _);
  350. var Marionette = (function(global, Backbone, _){
  351. "use strict";
  352. // Define and export the Marionette namespace
  353. var Marionette = {};
  354. Backbone.Marionette = Marionette;
  355. // Get the DOM manipulator for later use
  356. Marionette.$ = Backbone.$;
  357. // Helpers
  358. // -------
  359. // For slicing `arguments` in functions
  360. var protoSlice = Array.prototype.slice;
  361. function slice(args) {
  362. return protoSlice.call(args);
  363. }
  364. function throwError(message, name) {
  365. var error = new Error(message);
  366. error.name = name || 'Error';
  367. throw error;
  368. }
  369. // Marionette.extend
  370. // -----------------
  371. // Borrow the Backbone `extend` method so we can use it as needed
  372. Marionette.extend = Backbone.Model.extend;
  373. // Marionette.getOption
  374. // --------------------
  375. // Retrieve an object, function or other value from a target
  376. // object or its `options`, with `options` taking precedence.
  377. Marionette.getOption = function(target, optionName){
  378. if (!target || !optionName){ return; }
  379. var value;
  380. if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
  381. value = target.options[optionName];
  382. } else {
  383. value = target[optionName];
  384. }
  385. return value;
  386. };
  387. // Trigger an event and/or a corresponding method name. Examples:
  388. //
  389. // `this.triggerMethod("foo")` will trigger the "foo" event and
  390. // call the "onFoo" method.
  391. //
  392. // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
  393. // call the "onFooBar" method.
  394. Marionette.triggerMethod = (function(){
  395. // split the event name on the :
  396. var splitter = /(^|:)(\w)/gi;
  397. // take the event section ("section1:section2:section3")
  398. // and turn it in to uppercase name
  399. function getEventName(match, prefix, eventName) {
  400. return eventName.toUpperCase();
  401. }
  402. // actual triggerMethod name
  403. var triggerMethod = function(event) {
  404. // get the method name from the event name
  405. var methodName = 'on' + event.replace(splitter, getEventName);
  406. var method = this[methodName];
  407. // trigger the event, if a trigger method exists
  408. if(_.isFunction(this.trigger)) {
  409. this.trigger.apply(this, arguments);
  410. }
  411. // call the onMethodName if it exists
  412. if (_.isFunction(method)) {
  413. // pass all arguments, except the event name
  414. return method.apply(this, _.tail(arguments));
  415. }
  416. };
  417. return triggerMethod;
  418. })();
  419. // DOMRefresh
  420. // ----------
  421. //
  422. // Monitor a view's state, and after it has been rendered and shown
  423. // in the DOM, trigger a "dom:refresh" event every time it is
  424. // re-rendered.
  425. Marionette.MonitorDOMRefresh = (function(){
  426. // track when the view has been shown in the DOM,
  427. // using a Marionette.Region (or by other means of triggering "show")
  428. function handleShow(view){
  429. view._isShown = true;
  430. triggerDOMRefresh(view);
  431. }
  432. // track when the view has been rendered
  433. function handleRender(view){
  434. view._isRendered = true;
  435. triggerDOMRefresh(view);
  436. }
  437. // Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
  438. function triggerDOMRefresh(view){
  439. if (view._isShown && view._isRendered){
  440. if (_.isFunction(view.triggerMethod)){
  441. view.triggerMethod("dom:refresh");
  442. }
  443. }
  444. }
  445. // Export public API
  446. return function(view){
  447. view.listenTo(view, "show", function(){
  448. handleShow(view);
  449. });
  450. view.listenTo(view, "render", function(){
  451. handleRender(view);
  452. });
  453. };
  454. })();
  455. // Marionette.bindEntityEvents & unbindEntityEvents
  456. // ---------------------------
  457. //
  458. // These methods are used to bind/unbind a backbone "entity" (collection/model)
  459. // to methods on a target object.
  460. //
  461. // The first parameter, `target`, must have a `listenTo` method from the
  462. // EventBinder object.
  463. //
  464. // The second parameter is the entity (Backbone.Model or Backbone.Collection)
  465. // to bind the events from.
  466. //
  467. // The third parameter is a hash of { "event:name": "eventHandler" }
  468. // configuration. Multiple handlers can be separated by a space. A
  469. // function can be supplied instead of a string handler name.
  470. (function(Marionette){
  471. "use strict";
  472. // Bind the event to handlers specified as a string of
  473. // handler names on the target object
  474. function bindFromStrings(target, entity, evt, methods){
  475. var methodNames = methods.split(/\s+/);
  476. _.each(methodNames,function(methodName) {
  477. var method = target[methodName];
  478. if(!method) {
  479. throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
  480. }
  481. target.listenTo(entity, evt, method, target);
  482. });
  483. }
  484. // Bind the event to a supplied callback function
  485. function bindToFunction(target, entity, evt, method){
  486. target.listenTo(entity, evt, method, target);
  487. }
  488. // Bind the event to handlers specified as a string of
  489. // handler names on the target object
  490. function unbindFromStrings(target, entity, evt, methods){
  491. var methodNames = methods.split(/\s+/);
  492. _.each(methodNames,function(methodName) {
  493. var method = target[methodName];
  494. target.stopListening(entity, evt, method, target);
  495. });
  496. }
  497. // Bind the event to a supplied callback function
  498. function unbindToFunction(target, entity, evt, method){
  499. target.stopListening(entity, evt, method, target);
  500. }
  501. // generic looping function
  502. function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
  503. if (!entity || !bindings) { return; }
  504. // allow the bindings to be a function
  505. if (_.isFunction(bindings)){
  506. bindings = bindings.call(target);
  507. }
  508. // iterate the bindings and bind them
  509. _.each(bindings, function(methods, evt){
  510. // allow for a function as the handler,
  511. // or a list of event names as a string
  512. if (_.isFunction(methods)){
  513. functionCallback(target, entity, evt, methods);
  514. } else {
  515. stringCallback(target, entity, evt, methods);
  516. }
  517. });
  518. }
  519. // Export Public API
  520. Marionette.bindEntityEvents = function(target, entity, bindings){
  521. iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
  522. };
  523. Marionette.unbindEntityEvents = function(target, entity, bindings){
  524. iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
  525. };
  526. })(Marionette);
  527. // Callbacks
  528. // ---------
  529. // A simple way of managing a collection of callbacks
  530. // and executing them at a later point in time, using jQuery's
  531. // `Deferred` object.
  532. Marionette.Callbacks = function(){
  533. this._deferred = Marionette.$.Deferred();
  534. this._callbacks = [];
  535. };
  536. _.extend(Marionette.Callbacks.prototype, {
  537. // Add a callback to be executed. Callbacks added here are
  538. // guaranteed to execute, even if they are added after the
  539. // `run` method is called.
  540. add: function(callback, contextOverride){
  541. this._callbacks.push({cb: callback, ctx: contextOverride});
  542. this._deferred.done(function(context, options){
  543. if (contextOverride){ context = contextOverride; }
  544. callback.call(context, options);
  545. });
  546. },
  547. // Run all registered callbacks with the context specified.
  548. // Additional callbacks can be added after this has been run
  549. // and they will still be executed.
  550. run: function(options, context){
  551. this._deferred.resolve(context, options);
  552. },
  553. // Resets the list of callbacks to be run, allowing the same list
  554. // to be run multiple times - whenever the `run` method is called.
  555. reset: function(){
  556. var callbacks = this._callbacks;
  557. this._deferred = Marionette.$.Deferred();
  558. this._callbacks = [];
  559. _.each(callbacks, function(cb){
  560. this.add(cb.cb, cb.ctx);
  561. }, this);
  562. }
  563. });
  564. // Marionette Controller
  565. // ---------------------
  566. //
  567. // A multi-purpose object to use as a controller for
  568. // modules and routers, and as a mediator for workflow
  569. // and coordination of other objects, views, and more.
  570. Marionette.Controller = function(options){
  571. this.triggerMethod = Marionette.triggerMethod;
  572. this.options = options || {};
  573. if (_.isFunction(this.initialize)){
  574. this.initialize(this.options);
  575. }
  576. };
  577. Marionette.Controller.extend = Marionette.extend;
  578. // Controller Methods
  579. // --------------
  580. // Ensure it can trigger events with Backbone.Events
  581. _.extend(Marionette.Controller.prototype, Backbone.Events, {
  582. close: function(){
  583. this.stopListening();
  584. this.triggerMethod("close");
  585. this.unbind();
  586. }
  587. });
  588. // Region
  589. // ------
  590. //
  591. // Manage the visual regions of your composite application. See
  592. // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
  593. Marionette.Region = function(options){
  594. this.options = options || {};
  595. this.el = Marionette.getOption(this, "el");
  596. if (!this.el){
  597. var err = new Error("An 'el' must be specified for a region.");
  598. err.name = "NoElError";
  599. throw err;
  600. }
  601. if (this.initialize){
  602. var args = Array.prototype.slice.apply(arguments);
  603. this.initialize.apply(this, args);
  604. }
  605. };
  606. // Region Type methods
  607. // -------------------
  608. _.extend(Marionette.Region, {
  609. // Build an instance of a region by passing in a configuration object
  610. // and a default region type to use if none is specified in the config.
  611. //
  612. // The config object should either be a string as a jQuery DOM selector,
  613. // a Region type directly, or an object literal that specifies both
  614. // a selector and regionType:
  615. //
  616. // ```js
  617. // {
  618. // selector: "#foo",
  619. // regionType: MyCustomRegion
  620. // }
  621. // ```
  622. //
  623. buildRegion: function(regionConfig, defaultRegionType){
  624. var regionIsString = (typeof regionConfig === "string");
  625. var regionSelectorIsString = (typeof regionConfig.selector === "string");
  626. var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
  627. var regionIsType = (typeof regionConfig === "function");
  628. if (!regionIsType && !regionIsString && !regionSelectorIsString) {
  629. throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
  630. }
  631. var selector, RegionType;
  632. // get the selector for the region
  633. if (regionIsString) {
  634. selector = regionConfig;
  635. }
  636. if (regionConfig.selector) {
  637. selector = regionConfig.selector;
  638. }
  639. // get the type for the region
  640. if (regionIsType){
  641. RegionType = regionConfig;
  642. }
  643. if (!regionIsType && regionTypeIsUndefined) {
  644. RegionType = defaultRegionType;
  645. }
  646. if (regionConfig.regionType) {
  647. RegionType = regionConfig.regionType;
  648. }
  649. // build the region instance
  650. var region = new RegionType({
  651. el: selector
  652. });
  653. // override the `getEl` function if we have a parentEl
  654. // this must be overridden to ensure the selector is found
  655. // on the first use of the region. if we try to assign the
  656. // region's `el` to `parentEl.find(selector)` in the object
  657. // literal to build the region, the element will not be
  658. // guaranteed to be in the DOM already, and will cause problems
  659. if (regionConfig.parentEl){
  660. region.getEl = function(selector) {
  661. var parentEl = regionConfig.parentEl;
  662. if (_.isFunction(parentEl)){
  663. parentEl = parentEl();
  664. }
  665. return parentEl.find(selector);
  666. };
  667. }
  668. return region;
  669. }
  670. });
  671. // Region Instance Methods
  672. // -----------------------
  673. _.extend(Marionette.Region.prototype, Backbone.Events, {
  674. // Displays a backbone view instance inside of the region.
  675. // Handles calling the `render` method for you. Reads content
  676. // directly from the `el` attribute. Also calls an optional
  677. // `onShow` and `close` method on your view, just after showing
  678. // or just before closing the view, respectively.
  679. show: function(view){
  680. this.ensureEl();
  681. var isViewClosed = view.isClosed || _.isUndefined(view.$el);
  682. var isDifferentView = view !== this.currentView;
  683. if (isDifferentView) {
  684. this.close();
  685. }
  686. view.render();
  687. if (isDifferentView || isViewClosed) {
  688. this.open(view);
  689. }
  690. this.currentView = view;
  691. Marionette.triggerMethod.call(this, "show", view);
  692. Marionette.triggerMethod.call(view, "show");
  693. },
  694. ensureEl: function(){
  695. if (!this.$el || this.$el.length === 0){
  696. this.$el = this.getEl(this.el);
  697. }
  698. },
  699. // Override this method to change how the region finds the
  700. // DOM element that it manages. Return a jQuery selector object.
  701. getEl: function(selector){
  702. return Marionette.$(selector);
  703. },
  704. // Override this method to change how the new view is
  705. // appended to the `$el` that the region is managing
  706. open: function(view){
  707. this.$el.empty().append(view.el);
  708. },
  709. // Close the current view, if there is one. If there is no
  710. // current view, it does nothing and returns immediately.
  711. close: function(){
  712. var view = this.currentView;
  713. if (!view || view.isClosed){ return; }
  714. // call 'close' or 'remove', depending on which is found
  715. if (view.close) { view.close(); }
  716. else if (view.remove) { view.remove(); }
  717. Marionette.triggerMethod.call(this, "close");
  718. delete this.currentView;
  719. },
  720. // Attach an existing view to the region. This
  721. // will not call `render` or `onShow` for the new view,
  722. // and will not replace the current HTML for the `el`
  723. // of the region.
  724. attachView: function(view){
  725. this.currentView = view;
  726. },
  727. // Reset the region by closing any existing view and
  728. // clearing out the cached `$el`. The next time a view
  729. // is shown via this region, the region will re-query the
  730. // DOM for the region's `el`.
  731. reset: function(){
  732. this.close();
  733. delete this.$el;
  734. }
  735. });
  736. // Copy the `extend` function used by Backbone's classes
  737. Marionette.Region.extend = Marionette.extend;
  738. // Marionette.RegionManager
  739. // ------------------------
  740. //
  741. // Manage one or more related `Marionette.Region` objects.
  742. Marionette.RegionManager = (function(Marionette){
  743. var RegionManager = Marionette.Controller.extend({
  744. constructor: function(options){
  745. this._regions = {};
  746. Marionette.Controller.prototype.constructor.call(this, options);
  747. },
  748. // Add multiple regions using an object literal, where
  749. // each key becomes the region name, and each value is
  750. // the region definition.
  751. addRegions: function(regionDefinitions, defaults){
  752. var regions = {};
  753. _.each(regionDefinitions, function(definition, name){
  754. if (typeof definition === "string"){
  755. definition = { selector: definition };
  756. }
  757. if (definition.selector){
  758. definition = _.defaults({}, definition, defaults);
  759. }
  760. var region = this.addRegion(name, definition);
  761. regions[name] = region;
  762. }, this);
  763. return regions;
  764. },
  765. // Add an individual region to the region manager,
  766. // and return the region instance
  767. addRegion: function(name, definition){
  768. var region;
  769. var isObject = _.isObject(definition);
  770. var isString = _.isString(definition);
  771. var hasSelector = !!definition.selector;
  772. if (isString || (isObject && hasSelector)){
  773. region = Marionette.Region.buildRegion(definition, Marionette.Region);
  774. } else if (_.isFunction(definition)){
  775. region = Marionette.Region.buildRegion(definition, Marionette.Region);
  776. } else {
  777. region = definition;
  778. }
  779. this._store(name, region);
  780. this.triggerMethod("region:add", name, region);
  781. return region;
  782. },
  783. // Get a region by name
  784. get: function(name){
  785. return this._regions[name];
  786. },
  787. // Remove a region by name
  788. removeRegion: function(name){
  789. var region = this._regions[name];
  790. this._remove(name, region);
  791. },
  792. // Close all regions in the region manager, and
  793. // remove them
  794. removeRegions: function(){
  795. _.each(this._regions, function(region, name){
  796. this._remove(name, region);
  797. }, this);
  798. },
  799. // Close all regions in the region manager, but
  800. // leave them attached
  801. closeRegions: function(){
  802. _.each(this._regions, function(region, name){
  803. region.close();
  804. }, this);
  805. },
  806. // Close all regions and shut down the region
  807. // manager entirely
  808. close: function(){
  809. this.removeRegions();
  810. var args = Array.prototype.slice.call(arguments);
  811. Marionette.Controller.prototype.close.apply(this, args);
  812. },
  813. // internal method to store regions
  814. _store: function(name, region){
  815. this._regions[name] = region;
  816. this._setLength();
  817. },
  818. // internal method to remove a region
  819. _remove: function(name, region){
  820. region.close();
  821. delete this._regions[name];
  822. this._setLength();
  823. this.triggerMethod("region:remove", name, region);
  824. },
  825. // set the number of regions current held
  826. _setLength: function(){
  827. this.length = _.size(this._regions);
  828. }
  829. });
  830. // Borrowing this code from Backbone.Collection:
  831. // http://backbonejs.org/docs/backbone.html#section-106
  832. //
  833. // Mix in methods from Underscore, for iteration, and other
  834. // collection related features.
  835. var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
  836. 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
  837. 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
  838. 'last', 'without', 'isEmpty', 'pluck'];
  839. _.each(methods, function(method) {
  840. RegionManager.prototype[method] = function() {
  841. var regions = _.values(this._regions);
  842. var args = [regions].concat(_.toArray(arguments));
  843. return _[method].apply(_, args);
  844. };
  845. });
  846. return RegionManager;
  847. })(Marionette);
  848. // Template Cache
  849. // --------------
  850. // Manage templates stored in `<script>` blocks,
  851. // caching them for faster access.
  852. Marionette.TemplateCache = function(templateId){
  853. this.templateId = templateId;
  854. };
  855. // TemplateCache object-level methods. Manage the template
  856. // caches from these method calls instead of creating
  857. // your own TemplateCache instances
  858. _.extend(Marionette.TemplateCache, {
  859. templateCaches: {},
  860. // Get the specified template by id. Either
  861. // retrieves the cached version, or loads it
  862. // from the DOM.
  863. get: function(templateId){
  864. var cachedTemplate = this.templateCaches[templateId];
  865. if (!cachedTemplate){
  866. cachedTemplate = new Marionette.TemplateCache(templateId);
  867. this.templateCaches[templateId] = cachedTemplate;
  868. }
  869. return cachedTemplate.load();
  870. },
  871. // Clear templates from the cache. If no arguments
  872. // are specified, clears all templates:
  873. // `clear()`
  874. //
  875. // If arguments are specified, clears each of the
  876. // specified templates from the cache:
  877. // `clear("#t1", "#t2", "...")`
  878. clear: function(){
  879. var i;
  880. var args = slice(arguments);
  881. var length = args.length;
  882. if (length > 0){
  883. for(i=0; i<length; i++){
  884. delete this.templateCaches[args[i]];
  885. }
  886. } else {
  887. this.templateCaches = {};
  888. }
  889. }
  890. });
  891. // TemplateCache instance methods, allowing each
  892. // template cache object to manage its own state
  893. // and know whether or not it has been loaded
  894. _.extend(Marionette.TemplateCache.prototype, {
  895. // Internal method to load the template
  896. load: function(){
  897. // Guard clause to prevent loading this template more than once
  898. if (this.compiledTemplate){
  899. return this.compiledTemplate;
  900. }
  901. // Load the template and compile it
  902. var template = this.loadTemplate(this.templateId);
  903. this.compiledTemplate = this.compileTemplate(template);
  904. return this.compiledTemplate;
  905. },
  906. // Load a template from the DOM, by default. Override
  907. // this method to provide your own template retrieval
  908. // For asynchronous loading with AMD/RequireJS, consider
  909. // using a template-loader plugin as described here:
  910. // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
  911. loadTemplate: function(templateId){
  912. var template = Marionette.$(templateId).html();
  913. if (!template || template.length === 0){
  914. throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
  915. }
  916. return template;
  917. },
  918. // Pre-compile the template before caching it. Override
  919. // this method if you do not need to pre-compile a template
  920. // (JST / RequireJS for example) or if you want to change
  921. // the template engine used (Handebars, etc).
  922. compileTemplate: function(rawTemplate){
  923. return _.template(rawTemplate);
  924. }
  925. });
  926. // Renderer
  927. // --------
  928. // Render a template with data by passing in the template
  929. // selector and the data to render.
  930. Marionette.Renderer = {
  931. // Render a template with data. The `template` parameter is
  932. // passed to the `TemplateCache` object to retrieve the
  933. // template function. Override this method to provide your own
  934. // custom rendering and template handling for all of Marionette.
  935. render: function(template, data){
  936. if (!template) {
  937. var error = new Error("Cannot render the template since it's false, null or undefined.");
  938. error.name = "TemplateNotFoundError";
  939. throw error;
  940. }
  941. var templateFunc;
  942. if (typeof template === "function"){
  943. templateFunc = template;
  944. } else {
  945. templateFunc = Marionette.TemplateCache.get(template);
  946. }
  947. return templateFunc(data);
  948. }
  949. };
  950. // Marionette.View
  951. // ---------------
  952. // The core view type that other Marionette views extend from.
  953. Marionette.View = Backbone.View.extend({
  954. constructor: function(options){
  955. _.bindAll(this, "render");
  956. var args = Array.prototype.slice.apply(arguments);
  957. // this exposes view options to the view initializer
  958. // this is a backfill since backbone removed the assignment
  959. // of this.options
  960. // at some point however this may be removed
  961. this.options = options || {};
  962. Backbone.View.prototype.constructor.apply(this, args);
  963. Marionette.MonitorDOMRefresh(this);
  964. this.listenTo(this, "show", this.onShowCalled, this);
  965. },
  966. // import the "triggerMethod" to trigger events with corresponding
  967. // methods if the method exists
  968. triggerMethod: Marionette.triggerMethod,
  969. // Get the template for this view
  970. // instance. You can set a `template` attribute in the view
  971. // definition or pass a `template: "whatever"` parameter in
  972. // to the constructor options.
  973. getTemplate: function(){
  974. return Marionette.getOption(this, "template");
  975. },
  976. // Mix in template helper methods. Looks for a
  977. // `templateHelpers` attribute, which can either be an
  978. // object literal, or a function that returns an object
  979. // literal. All methods and attributes from this object
  980. // are copies to the object passed in.
  981. mixinTemplateHelpers: function(target){
  982. target = target || {};
  983. var templateHelpers = Marionette.getOption(this, "templateHelpers");
  984. if (_.isFunction(templateHelpers)){
  985. templateHelpers = templateHelpers.call(this);
  986. }
  987. return _.extend(target, templateHelpers);
  988. },
  989. // Configure `triggers` to forward DOM events to view
  990. // events. `triggers: {"click .foo": "do:foo"}`
  991. configureTriggers: function(){
  992. if (!this.triggers) { return; }
  993. var triggerEvents = {};
  994. // Allow `triggers` to be configured as a function
  995. var triggers = _.result(this, "triggers");
  996. // Configure the triggers, prevent default
  997. // action and stop propagation of DOM events
  998. _.each(triggers, function(value, key){
  999. var hasOptions = _.isObject(value);
  1000. var eventName = hasOptions ? value.event : value;
  1001. // build the event handler function for the DOM event
  1002. triggerEvents[key] = function(e){
  1003. // stop the event in its tracks
  1004. if (e) {
  1005. var prevent = e.preventDefault;
  1006. var stop = e.stopPropagation;
  1007. var shouldPrevent = hasOptions ? value.preventDefault : prevent;
  1008. var shouldStop = hasOptions ? value.stopPropagation : stop;
  1009. if (shouldPrevent && prevent) { prevent.apply(e); }
  1010. if (shouldStop && stop) { stop.apply(e); }
  1011. }
  1012. // build the args for the event
  1013. var args = {
  1014. view: this,
  1015. model: this.model,
  1016. collection: this.collection
  1017. };
  1018. // trigger the event
  1019. this.triggerMethod(eventName, args);
  1020. };
  1021. }, this);
  1022. return triggerEvents;
  1023. },
  1024. // Overriding Backbone.View's delegateEvents to handle
  1025. // the `triggers`, `modelEvents`, and `collectionEvents` configuration
  1026. delegateEvents: function(events){
  1027. this._delegateDOMEvents(events);
  1028. Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
  1029. Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
  1030. },
  1031. // internal method to delegate DOM events and triggers
  1032. _delegateDOMEvents: function(events){
  1033. events = events || this.events;
  1034. if (_.isFunction(events)){ events = events.call(this); }
  1035. var combinedEvents = {};
  1036. var triggers = this.configureTriggers();
  1037. _.extend(combinedEvents, events, triggers);
  1038. Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
  1039. },
  1040. // Overriding Backbone.View's undelegateEvents to handle unbinding
  1041. // the `triggers`, `modelEvents`, and `collectionEvents` config
  1042. undelegateEvents: function(){
  1043. var args = Array.prototype.slice.call(arguments);
  1044. Backbone.View.prototype.undelegateEvents.apply(this, args);
  1045. Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
  1046. Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
  1047. },
  1048. // Internal method, handles the `show` event.
  1049. onShowCalled: function(){},
  1050. // Default `close` implementation, for removing a view from the
  1051. // DOM and unbinding it. Regions will call this method
  1052. // for you. You can specify an `onClose` method in your view to
  1053. // add custom code that is called after the view is closed.
  1054. close: function(){
  1055. if (this.isClosed) { return; }
  1056. // allow the close to be stopped by returning `false`
  1057. // from the `onBeforeClose` method
  1058. var shouldClose = this.triggerMethod("before:close");
  1059. if (shouldClose === false){
  1060. return;
  1061. }
  1062. // mark as closed before doing the actual close, to
  1063. // prevent infinite loops within "close" event handlers
  1064. // that are trying to close other views
  1065. this.isClosed = true;
  1066. this.triggerMethod("close");
  1067. // unbind UI elements
  1068. this.unbindUIElements();
  1069. // remove the view from the DOM
  1070. this.remove();
  1071. },
  1072. // This method binds the elements specified in the "ui" hash inside the view's code with
  1073. // the associated jQuery selectors.
  1074. bindUIElements: function(){
  1075. if (!this.ui) { return; }
  1076. // store the ui hash in _uiBindings so they can be reset later
  1077. // and so re-rendering the view will be able to find the bindings
  1078. if (!this._uiBindings){
  1079. this._uiBindings = this.ui;
  1080. }
  1081. // get the bindings result, as a function or otherwise
  1082. var bindings = _.result(this, "_uiBindings");
  1083. // empty the ui so we don't have anything to start with
  1084. this.ui = {};
  1085. // bind each of the selectors
  1086. _.each(_.keys(bindings), function(key) {
  1087. var selector = bindings[key];
  1088. this.ui[key] = this.$(selector);
  1089. }, this);
  1090. },
  1091. // This method unbinds the elements specified in the "ui" hash
  1092. unbindUIElements: function(){
  1093. if (!this.ui || !this._uiBindings){ return; }
  1094. // delete all of the existing ui bindings
  1095. _.each(this.ui, function($el, name){
  1096. delete this.ui[name];
  1097. }, this);
  1098. // reset the ui element to the original bindings configuration
  1099. this.ui = this._uiBindings;
  1100. delete this._uiBindings;
  1101. }
  1102. });
  1103. // Item View
  1104. // ---------
  1105. // A single item view implementation that contains code for rendering
  1106. // with underscore.js templates, serializing the view's model or collection,
  1107. // and calling several methods on extended views, such as `onRender`.
  1108. Marionette.ItemView = Marionette.View.extend({
  1109. // Setting up the inheritance chain which allows changes to
  1110. // Marionette.View.prototype.constructor which allows overriding
  1111. constructor: function(){
  1112. Marionette.View.prototype.constructor.apply(this, slice(arguments));
  1113. },
  1114. // Serialize the model or collection for the view. If a model is
  1115. // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
  1116. // is also called, but is used to populate an `items` array in the
  1117. // resulting data. If both are found, defaults to the model.
  1118. // You can override the `serializeData` method in your own view
  1119. // definition, to provide custom serialization for your view's data.
  1120. serializeData: function(){
  1121. var data = {};
  1122. if (this.model) {
  1123. data = this.model.toJSON();
  1124. }
  1125. else if (this.collection) {
  1126. data = { items: this.collection.toJSON() };
  1127. }
  1128. return data;
  1129. },
  1130. // Render the view, defaulting to underscore.js templates.
  1131. // You can override this in your view definition to provide
  1132. // a very specific rendering for your view. In general, though,
  1133. // you should override the `Marionette.Renderer` object to
  1134. // change how Marionette renders views.
  1135. render: function(){
  1136. this.isClosed = false;
  1137. this.triggerMethod("before:render", this);
  1138. this.triggerMethod("item:before:render", this);
  1139. var data = this.serializeData();
  1140. data = this.mixinTemplateHelpers(data);
  1141. var template = this.getTemplate();
  1142. var html = Marionette.Renderer.render(template, data);
  1143. this.$el.html(html);
  1144. this.bindUIElements();
  1145. this.triggerMethod("render", this);
  1146. this.triggerMethod("item:rendered", this);
  1147. return this;
  1148. },
  1149. // Override the default close event to add a few
  1150. // more events that are triggered.
  1151. close: function(){
  1152. if (this.isClosed){ return; }
  1153. this.triggerMethod('item:before:close');
  1154. Marionette.View.prototype.close.apply(this, slice(arguments));
  1155. this.triggerMethod('item:closed');
  1156. }
  1157. });
  1158. // Collection View
  1159. // ---------------
  1160. // A view that iterates over a Backbone.Collection
  1161. // and renders an individual ItemView for each model.
  1162. Marionette.CollectionView = Marionette.View.extend({
  1163. // used as the prefix for item view events
  1164. // that are forwarded through the collectionview
  1165. itemViewEventPrefix: "itemview",
  1166. // constructor
  1167. constructor: function(options){
  1168. this._initChildViewStorage();
  1169. Marionette.View.prototype.constructor.apply(this, slice(arguments));
  1170. this._initialEvents();
  1171. },
  1172. // Configured the initial events that the collection view
  1173. // binds to. Override this method to prevent the initial
  1174. // events, or to add your own initial events.
  1175. _initialEvents: function(){
  1176. if (this.collection){
  1177. this.listenTo(this.collection, "add", this.addChildView, this);
  1178. this.listenTo(this.collection, "remove", this.removeItemView, this);
  1179. this.listenTo(this.collection, "reset", this.render, this);
  1180. }
  1181. },
  1182. // Handle a child item added to the collection
  1183. addChildView: function(item, collection, options){
  1184. this.closeEmptyView();
  1185. var ItemView = this.getItemView(item);
  1186. var index = this.collection.indexOf(item);
  1187. this.addItemView(item, ItemView, index);
  1188. },
  1189. // Override from `Marionette.View` to guarantee the `onShow` method
  1190. // of child views is called.
  1191. onShowCalled: function(){
  1192. this.children.each(function(child){
  1193. Marionette.triggerMethod.call(child, "show");
  1194. });
  1195. },
  1196. // Internal method to trigger the before render callbacks
  1197. // and events
  1198. triggerBeforeRender: function(){
  1199. this.triggerMethod("before:render", this);
  1200. this.triggerMethod("collection:before:render", this);
  1201. },
  1202. // Internal method to trigger the rendered callbacks and
  1203. // events
  1204. triggerRendered: function(){
  1205. this.triggerMethod("render", this);
  1206. this.triggerMethod("collection:rendered", this);
  1207. },
  1208. // Render the collection of items. Override this method to
  1209. // provide your own implementation of a render function for
  1210. // the collection view.
  1211. render: function(){
  1212. this.isClosed = false;
  1213. this.triggerBeforeRender();
  1214. this._renderChildren();
  1215. this.triggerRendered();
  1216. return this;
  1217. },
  1218. // Internal method. Separated so that CompositeView can have
  1219. // more control over events being triggered, around the rendering
  1220. // process
  1221. _renderChildren: function(){
  1222. this.closeEmptyView();
  1223. this.closeChildren();
  1224. if (this.collection && this.collection.length > 0) {
  1225. this.showCollection();
  1226. } else {
  1227. this.showEmptyView();
  1228. }
  1229. },
  1230. // Internal method to loop through each item in the
  1231. // collection view and show it
  1232. showCollection: function(){
  1233. var ItemView;
  1234. this.collection.each(function(item, index){
  1235. ItemView = this.getItemView(item);
  1236. this.addItemView(item, ItemView, index);
  1237. }, this);
  1238. },
  1239. // Internal method to show an empty view in place of
  1240. // a collection of item views, when the collection is
  1241. // empty
  1242. showEmptyView: function(){
  1243. var EmptyView = this.getEmptyView();
  1244. if (EmptyView && !this._showingEmptyView){
  1245. this._showingEmptyView = true;
  1246. var model = new Backbone.Model();
  1247. this.addItemView(model, EmptyView, 0);
  1248. }
  1249. },
  1250. // Internal method to close an existing emptyView instance
  1251. // if one exists. Called when a collection view has been
  1252. // rendered empty, and then an item is added to the collection.
  1253. closeEmptyView: function(){
  1254. if (this._showingEmptyView){
  1255. this.closeChildren();
  1256. delete this._showingEmptyView;
  1257. }
  1258. },
  1259. // Retrieve the empty view type
  1260. getEmptyView: function(){
  1261. return Marionette.getOption(this, "emptyView");
  1262. },
  1263. // Retrieve the itemView type, either from `this.options.itemView`
  1264. // or from the `itemView` in the object definition. The "options"
  1265. // takes precedence.
  1266. getItemView: function(item){
  1267. var itemView = Marionette.getOption(this, "itemView");
  1268. if (!itemView){
  1269. throwError("An `itemView` must be specified", "NoItemViewError");
  1270. }
  1271. return itemView;
  1272. },
  1273. // Render the child item's view and add it to the
  1274. // HTML for the collection view.
  1275. addItemView: function(item, ItemView, index){
  1276. // get the itemViewOptions if any were specified
  1277. var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
  1278. if (_.isFunction(itemViewOptions)){
  1279. itemViewOptions = itemViewOptions.call(this, item, index);
  1280. }
  1281. // build the view
  1282. var view = this.buildItemView(item, ItemView, itemViewOptions);
  1283. // set up the child view event forwarding
  1284. this.addChildViewEventForwarding(view);
  1285. // this view is about to be added
  1286. this.triggerMethod("before:item:added", view);
  1287. // Store the child view itself so we can properly
  1288. // remove and/or close it later
  1289. this.children.add(view);
  1290. // Render it and show it
  1291. this.renderItemView(view, index);
  1292. // call the "show" method if the collection view
  1293. // has already been shown
  1294. if (this._isShown){
  1295. Marionette.triggerMethod.call(view, "show");
  1296. }
  1297. // this view was added
  1298. this.triggerMethod("after:item:added", view);
  1299. },
  1300. // Set up the child view event forwarding. Uses an "itemview:"
  1301. // prefix in front of all forwarded events.
  1302. addChildViewEventForwarding: function(view){
  1303. var prefix = Marionette.getOption(this, "itemViewEventPrefix");
  1304. // Forward all child item view events through the parent,
  1305. // prepending "itemview:" to the event name
  1306. this.listenTo(view, "all", function(){
  1307. var args = slice(arguments);
  1308. args[0] = prefix + ":" + args[0];
  1309. args.splice(1, 0, view);
  1310. Marionette.triggerMethod.apply(this, args);
  1311. }, this);
  1312. },
  1313. // render the item view
  1314. renderItemView: function(view, index) {
  1315. view.render();
  1316. this.appendHtml(this, view, index);
  1317. },
  1318. // Build an `itemView` for every model in the collection.
  1319. buildItemView: function(item, ItemViewType, itemViewOptions){
  1320. var options = _.extend({model: item}, itemViewOptions);
  1321. return new ItemViewType(options);
  1322. },
  1323. // get the child view by item it holds, and remove it
  1324. removeItemView: function(item){
  1325. var view = this.children.findByModel(item);
  1326. this.removeChildView(view);
  1327. this.checkEmpty();
  1328. },
  1329. // Remove the child view and close it
  1330. removeChildView: function(view){
  1331. // shut down the child view properly,
  1332. // including events that the collection has from it
  1333. if (view){
  1334. this.stopListening(view);
  1335. // call 'close' or 'remove', depending on which is found
  1336. if (view.close) { view.close(); }
  1337. else if (view.remove) { view.remove(); }
  1338. this.children.remove(view);
  1339. }
  1340. this.triggerMethod("item:removed", view);
  1341. },
  1342. // helper to show the empty view if the collection is empty
  1343. checkEmpty: function() {
  1344. // check if we're empty now, and if we are, show the
  1345. // empty view
  1346. if (!this.collection || this.collection.length === 0){
  1347. this.showEmptyView();
  1348. }
  1349. },
  1350. // Append the HTML to the collection's `el`.
  1351. // Override this method to do something other
  1352. // then `.append`.
  1353. appendHtml: function(collectionView, itemView, index){
  1354. collectionView.$el.append(itemView.el);
  1355. },
  1356. // Internal method to set up the `children` object for
  1357. // storing all of the child views
  1358. _initChildViewStorage: function(){
  1359. this.children = new Backbone.ChildViewContainer();
  1360. },
  1361. // Handle cleanup and other closing needs for
  1362. // the collection of views.
  1363. close: function(){
  1364. if (this.isClosed){ return; }
  1365. this.triggerMethod("collection:before:close");
  1366. this.closeChildren();
  1367. this.triggerMethod("collection:closed");
  1368. Marionette.View.prototype.close.apply(this, slice(arguments));
  1369. },
  1370. // Close the child views that this collection view
  1371. // is holding on to, if any
  1372. closeChildren: function(){
  1373. this.children.each(function(child){
  1374. this.removeChildView(child);
  1375. }, this);
  1376. this.checkEmpty();
  1377. }
  1378. });
  1379. // Composite View
  1380. // --------------
  1381. // Used for rendering a branch-leaf, hierarchical structure.
  1382. // Extends directly from CollectionView and also renders an
  1383. // an item view as `modelView`, for the top leaf
  1384. Marionette.CompositeView = Marionette.CollectionView.extend({
  1385. // Setting up the inheritance chain which allows changes to
  1386. // Marionette.CollectionView.prototype.constructor which allows overriding
  1387. constructor: function(){
  1388. Marionette.CollectionView.prototype.constructor.apply(this, slice(arguments));
  1389. },
  1390. // Configured the initial events that the composite view
  1391. // binds to. Override this method to prevent the initial
  1392. // events, or to add your own initial events.
  1393. _initialEvents: function(){
  1394. if (this.collection){
  1395. this.listenTo(this.collection, "add", this.addChildView, this);
  1396. this.listenTo(this.collection, "remove", this.removeItemView, this);
  1397. this.listenTo(this.collection, "reset", this._renderChildren, this);
  1398. }
  1399. },
  1400. // Retrieve the `itemView` to be used when rendering each of
  1401. // the items in the collection. The default is to return
  1402. // `this.itemView` or Marionette.CompositeView if no `itemView`
  1403. // has been defined
  1404. getItemView: function(item){
  1405. var itemView = Marionette.getOption(this, "itemView") || this.constructor;
  1406. if (!itemView){
  1407. throwError("An `itemView` must be specified", "NoItemViewError");
  1408. }
  1409. return itemView;
  1410. },
  1411. // Serialize the collection for the view.
  1412. // You can override the `serializeData` method in your own view
  1413. // definition, to provide custom serialization for your view's data.
  1414. serializeData: function(){
  1415. var data = {};
  1416. if (this.model){
  1417. data = this.model.toJSON();
  1418. }
  1419. return data;
  1420. },
  1421. // Renders the model once, and the collection once. Calling
  1422. // this again will tell the model's view to re-render itself
  1423. // but the collection will not re-render.
  1424. render: function(){
  1425. this.isRendered = true;
  1426. this.isClosed = false;
  1427. this.resetItemViewContainer();
  1428. this.triggerBeforeRender();
  1429. var html = this.renderModel();
  1430. this.$el.html(html);
  1431. // the ui bindings is done here and not at the end of render since they
  1432. // will not be available until after the model is rendered, but should be
  1433. // available before the collection is rendered.
  1434. this.bindUIElements();
  1435. this.triggerMethod("composite:model:rendered");
  1436. this._renderChildren();
  1437. this.triggerMethod("composite:rendered");
  1438. this.triggerRendered();
  1439. return this;
  1440. },
  1441. _renderChildren: function(){
  1442. if (this.isRendered){
  1443. Marionette.CollectionView.prototype._renderChildren.call(this);
  1444. this.triggerMethod("composite:collection:rendered");
  1445. }
  1446. },
  1447. // Render an individual model, if we have one, as
  1448. // part of a composite view (branch / leaf). For example:
  1449. // a treeview.
  1450. renderModel: function(){
  1451. var data = {};
  1452. data = this.serializeData();
  1453. data = this.mixinTemplateHelpers(data);
  1454. var template = this.getTemplate();
  1455. return Marionette.Renderer.render(template, data);
  1456. },
  1457. // Appends the `el` of itemView instances to the specified
  1458. // `itemViewContainer` (a jQuery selector). Override this method to
  1459. // provide custom logic of how the child item view instances have their
  1460. // HTML appended to the composite view instance.
  1461. appendHtml: function(cv, iv, index){
  1462. var $container = this.getItemViewContainer(cv);
  1463. $container.append(iv.el);
  1464. },
  1465. // Internal method to ensure an `$itemViewContainer` exists, for the
  1466. // `appendHtml` method to use.
  1467. getItemViewContainer: function(containerView){
  1468. if ("$itemViewContainer" in containerView){
  1469. return containerView.$itemViewContainer;
  1470. }
  1471. var container;
  1472. var itemViewContainer = Marionette.getOption(containerView, "itemViewContainer");
  1473. if (itemViewContainer){
  1474. var selector = _.isFunction(itemViewContainer) ? itemViewContainer() : itemViewContainer;
  1475. container = containerView.$(selector);
  1476. if (container.length <= 0) {
  1477. throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
  1478. }
  1479. } else {
  1480. container = containerView.$el;
  1481. }
  1482. containerView.$itemViewContainer = container;
  1483. return container;
  1484. },
  1485. // Internal method to reset the `$itemViewContainer` on render
  1486. resetItemViewContainer: function(){
  1487. if (this.$itemViewContainer){
  1488. delete this.$itemViewContainer;
  1489. }
  1490. }
  1491. });
  1492. // Layout
  1493. // ------
  1494. // Used for managing application layouts, nested layouts and
  1495. // multiple regions within an application or sub-application.
  1496. //
  1497. // A specialized view type that renders an area of HTML and then
  1498. // attaches `Region` instances to the specified `regions`.
  1499. // Used for composite view management and sub-application areas.
  1500. Marionette.Layout = Marionette.ItemView.extend({
  1501. regionType: Marionette.Region,
  1502. // Ensure the regions are available when the `initialize` method
  1503. // is called.
  1504. constructor: function (options) {
  1505. options = options || {};
  1506. this._firstRender = true;
  1507. this._initializeRegions(options);
  1508. Marionette.ItemView.prototype.constructor.call(this, options);
  1509. },
  1510. // Layout's render will use the existing region objects the
  1511. // first time it is called. Subsequent calls will close the
  1512. // views that the regions are showing and then reset the `el`
  1513. // for the regions to the newly rendered DOM elements.
  1514. render: function(){
  1515. if (this.isClosed){
  1516. // a previously closed layout means we need to
  1517. // completely re-initialize the regions
  1518. this._initializeRegions();
  1519. }
  1520. if (this._firstRender) {
  1521. // if this is the first render, don't do anything to
  1522. // reset the regions
  1523. this._firstRender = false;
  1524. } else if (!this.isClosed){
  1525. // If this is not the first render call, then we need to
  1526. // re-initializing the `el` for each region
  1527. this._reInitializeRegions();
  1528. }
  1529. var args = Array.prototype.slice.apply(arguments);
  1530. var result = Marionette.ItemView.prototype.render.apply(this, args);
  1531. return result;
  1532. },
  1533. // Handle closing regions, and then close the view itself.
  1534. close: function () {
  1535. if (this.isClosed){ return; }
  1536. this.regionManager.close();
  1537. var args = Array.prototype.slice.apply(arguments);
  1538. Marionette.ItemView.prototype.close.apply(this, args);
  1539. },
  1540. // Add a single region, by name, to the layout
  1541. addRegion: function(name, definition){
  1542. var regions = {};
  1543. regions[name] = definition;
  1544. return this._buildRegions(regions)[name];
  1545. },
  1546. // Add multiple regions as a {name: definition, name2: def2} object literal
  1547. addRegions: function(regions){
  1548. this.regions = _.extend({}, this.regions, regions);
  1549. return this._buildRegions(regions);
  1550. },
  1551. // Remove a single region from the Layout, by name
  1552. removeRegion: function(name){
  1553. delete this.regions[name];
  1554. return this.regionManager.removeRegion(name);
  1555. },
  1556. // internal method to build regions
  1557. _buildRegions: function(regions){
  1558. var that = this;
  1559. var defaults = {
  1560. regionType: Marionette.getOption(this, "regionType"),
  1561. parentEl: function(){ return that.$el; }
  1562. };
  1563. return this.regionManager.addRegions(regions, defaults);
  1564. },
  1565. // Internal method to initialize the regions that have been defined in a
  1566. // `regions` attribute on this layout.
  1567. _initializeRegions: function (options) {
  1568. var regions;
  1569. this._initRegionManager();
  1570. if (_.isFunction(this.regions)) {
  1571. regions = this.regions(options);
  1572. } else {
  1573. regions = this.regions || {};
  1574. }
  1575. this.addRegions(regions);
  1576. },
  1577. // Internal method to re-initialize all of the regions by updating the `el` that
  1578. // they point to
  1579. _reInitializeRegions: function(){
  1580. this.regionManager.closeRegions();
  1581. this.regionManager.each(function(region){
  1582. region.reset();
  1583. });
  1584. },
  1585. // Internal method to initialize the region manager
  1586. // and all regions in it
  1587. _initRegionManager: function(){
  1588. this.regionManager = new Marionette.RegionManager();
  1589. this.listenTo(this.regionManager, "region:add", function(name, region){
  1590. this[name] = region;
  1591. this.trigger("region:add", name, region);
  1592. });
  1593. this.listenTo(this.regionManager, "region:remove", function(name, region){
  1594. delete this[name];
  1595. this.trigger("region:remove", name, region);
  1596. });
  1597. }
  1598. });
  1599. // AppRouter
  1600. // ---------
  1601. // Reduce the boilerplate code of handling route events
  1602. // and then calling a single method on another object.
  1603. // Have your routers configured to call the method on
  1604. // your object, directly.
  1605. //
  1606. // Configure an AppRouter with `appRoutes`.
  1607. //
  1608. // App routers can only take one `controller` object.
  1609. // It is recommended that you divide your controller
  1610. // objects in to smaller pieces of related functionality
  1611. // and have multiple routers / controllers, instead of
  1612. // just one giant router and controller.
  1613. //
  1614. // You can also add standard routes to an AppRouter.
  1615. Marionette.AppRouter = Backbone.Router.extend({
  1616. constructor: function(options){
  1617. Backbone.Router.prototype.constructor.apply(this, slice(arguments));
  1618. this.options = options || {};
  1619. var appRoutes = Marionette.getOption(this, "appRoutes");
  1620. var controller = this._getController();
  1621. this.processAppRoutes(controller, appRoutes);
  1622. },
  1623. // Similar to route method on a Backbone Router but
  1624. // method is called on the controller
  1625. appRoute: function(route, methodName) {
  1626. var controller = this._getController();
  1627. this._addAppRoute(controller, route, methodName);
  1628. },
  1629. // Internal method to process the `appRoutes` for the
  1630. // router, and turn them in to routes that trigger the
  1631. // specified method on the specified `controller`.
  1632. processAppRoutes: function(controller, appRoutes) {
  1633. if (!appRoutes){ return; }
  1634. var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
  1635. _.each(routeNames, function(route) {
  1636. this._addAppRoute(controller, route, appRoutes[route]);
  1637. }, this);
  1638. },
  1639. _getController: function(){
  1640. return Marionette.getOption(this, "controller");
  1641. },
  1642. _addAppRoute: function(controller, route, methodName){
  1643. var method = controller[methodName];
  1644. if (!method) {
  1645. throw new Error("Method '" + methodName + "' was not found on the controller");
  1646. }
  1647. this.route(route, methodName, _.bind(method, controller));
  1648. }
  1649. });
  1650. // Application
  1651. // -----------
  1652. // Contain and manage the composite application as a whole.
  1653. // Stores and starts up `Region` objects, includes an
  1654. // event aggregator as `app.vent`
  1655. Marionette.Application = function(options){
  1656. this._initRegionManager();
  1657. this._initCallbacks = new Marionette.Callbacks();
  1658. this.vent = new Backbone.Wreqr.EventAggregator();
  1659. this.commands = new Backbone.Wreqr.Commands();
  1660. this.reqres = new Backbone.Wreqr.RequestResponse();
  1661. this.submodules = {};
  1662. _.extend(this, options);
  1663. this.triggerMethod = Marionette.triggerMethod;
  1664. };
  1665. _.extend(Marionette.Application.prototype, Backbone.Events, {
  1666. // Command execution, facilitated by Backbone.Wreqr.Commands
  1667. execute: function(){
  1668. var args = Array.prototype.slice.apply(arguments);
  1669. this.commands.execute.apply(this.commands, args);
  1670. },
  1671. // Request/response, facilitated by Backbone.Wreqr.RequestResponse
  1672. request: function(){
  1673. var args = Array.prototype.slice.apply(arguments);
  1674. return this.reqres.request.apply(this.reqres, args);
  1675. },
  1676. // Add an initializer that is either run at when the `start`
  1677. // method is called, or run immediately if added after `start`
  1678. // has already been called.
  1679. addInitializer: function(initializer){
  1680. this._initCallbacks.add(initializer);
  1681. },
  1682. // kick off all of the application's processes.
  1683. // initializes all of the regions that have been added
  1684. // to the app, and runs all of the initializer functions
  1685. start: function(options){
  1686. this.triggerMethod("initialize:before", options);
  1687. this._initCallbacks.run(options, this);
  1688. this.triggerMethod("initialize:after", options);
  1689. this.triggerMethod("start", options);
  1690. },
  1691. // Add regions to your app.
  1692. // Accepts a hash of named strings or Region objects
  1693. // addRegions({something: "#someRegion"})
  1694. // addRegions({something: Region.extend({el: "#someRegion"}) });
  1695. addRegions: function(regions){
  1696. return this._regionManager.addRegions(regions);
  1697. },
  1698. // Close all regions in the app, without removing them
  1699. closeRegions: function(){
  1700. this._regionManager.closeRegions();
  1701. },
  1702. // Removes a region from your app, by name
  1703. // Accepts the regions name
  1704. // removeRegion('myRegion')
  1705. removeRegion: function(region) {
  1706. this._regionManager.removeRegion(region);
  1707. },
  1708. // Provides alternative access to regions
  1709. // Accepts the region name
  1710. // getRegion('main')
  1711. getRegion: function(region) {
  1712. return this._regionManager.get(region);
  1713. },
  1714. // Create a module, attached to the application
  1715. module: function(moduleNames, moduleDefinition){
  1716. // slice the args, and add this application object as the
  1717. // first argument of the array
  1718. var args = slice(arguments);
  1719. args.unshift(this);
  1720. // see the Marionette.Module object for more information
  1721. return Marionette.Module.create.apply(Marionette.Module, args);
  1722. },
  1723. // Internal method to set up the region manager
  1724. _initRegionManager: function(){
  1725. this._regionManager = new Marionette.RegionManager();
  1726. this.listenTo(this._regionManager, "region:add", function(name, region){
  1727. this[name] = region;
  1728. });
  1729. this.listenTo(this._regionManager, "region:remove", function(name, region){
  1730. delete this[name];
  1731. });
  1732. }
  1733. });
  1734. // Copy the `extend` function used by Backbone's classes
  1735. Marionette.Application.extend = Marionette.extend;
  1736. // Module
  1737. // ------
  1738. // A simple module system, used to create privacy and encapsulation in
  1739. // Marionette applications
  1740. Marionette.Module = function(moduleName, app){
  1741. this.moduleName = moduleName;
  1742. // store sub-modules
  1743. this.submodules = {};
  1744. this._setupInitializersAndFinalizers();
  1745. // store the configuration for this module
  1746. this.app = app;
  1747. this.startWithParent = true;
  1748. this.triggerMethod = Marionette.triggerMethod;
  1749. };
  1750. // Extend the Module prototype with events / listenTo, so that the module
  1751. // can be used as an event aggregator or pub/sub.
  1752. _.extend(Marionette.Module.prototype, Backbone.Events, {
  1753. // Initializer for a specific module. Initializers are run when the
  1754. // module's `start` method is called.
  1755. addInitializer: function(callback){
  1756. this._initializerCallbacks.add(callback);
  1757. },
  1758. // Finalizers are run when a module is stopped. They are used to teardown
  1759. // and finalize any variables, references, events and other code that the
  1760. // module had set up.
  1761. addFinalizer: function(callback){
  1762. this._finalizerCallbacks.add(callback);
  1763. },
  1764. // Start the module, and run all of its initializers
  1765. start: function(options){
  1766. // Prevent re-starting a module that is already started
  1767. if (this._isInitialized){ return; }
  1768. // start the sub-modules (depth-first hierarchy)
  1769. _.each(this.submodules, function(mod){
  1770. // check to see if we should start the sub-module with this parent
  1771. if (mod.startWithParent){
  1772. mod.start(options);
  1773. }
  1774. });
  1775. // run the callbacks to "start" the current module
  1776. this.triggerMethod("before:start", options);
  1777. this._initializerCallbacks.run(options, this);
  1778. this._isInitialized = true;
  1779. this.triggerMethod("start", options);
  1780. },
  1781. // Stop this module by running its finalizers and then stop all of
  1782. // the sub-modules for this module
  1783. stop: function(){
  1784. // if we are not initialized, don't bother finalizing
  1785. if (!this._isInitialized){ return; }
  1786. this._isInitialized = false;
  1787. Marionette.triggerMethod.call(this, "before:stop");
  1788. // stop the sub-modules; depth-first, to make sure the
  1789. // sub-modules are stopped / finalized before parents
  1790. _.each(this.submodules, function(mod){ mod.stop(); });
  1791. // run the finalizers
  1792. this._finalizerCallbacks.run(undefined,this);
  1793. // reset the initializers and finalizers
  1794. this._initializerCallbacks.reset();
  1795. this._finalizerCallbacks.reset();
  1796. Marionette.triggerMethod.call(this, "stop");
  1797. },
  1798. // Configure the module with a definition function and any custom args
  1799. // that are to be passed in to the definition function
  1800. addDefinition: function(moduleDefinition, customArgs){
  1801. this._runModuleDefinition(moduleDefinition, customArgs);
  1802. },
  1803. // Internal method: run the module definition function with the correct
  1804. // arguments
  1805. _runModuleDefinition: function(definition, customArgs){
  1806. if (!definition){ return; }
  1807. // build the correct list of arguments for the module definition
  1808. var args = _.flatten([
  1809. this,
  1810. this.app,
  1811. Backbone,
  1812. Marionette,
  1813. Marionette.$, _,
  1814. customArgs
  1815. ]);
  1816. definition.apply(this, args);
  1817. },
  1818. // Internal method: set up new copies of initializers and finalizers.
  1819. // Calling this method will wipe out all existing initializers and
  1820. // finalizers.
  1821. _setupInitializersAndFinalizers: function(){
  1822. this._initializerCallbacks = new Marionette.Callbacks();
  1823. this._finalizerCallbacks = new Marionette.Callbacks();
  1824. }
  1825. });
  1826. // Type methods to create modules
  1827. _.extend(Marionette.Module, {
  1828. // Create a module, hanging off the app parameter as the parent object.
  1829. create: function(app, moduleNames, moduleDefinition){
  1830. var module = app;
  1831. // get the custom args passed in after the module definition and
  1832. // get rid of the module name and definition function
  1833. var customArgs = slice(arguments);
  1834. customArgs.splice(0, 3);
  1835. // split the module names and get the length
  1836. moduleNames = moduleNames.split(".");
  1837. var length = moduleNames.length;
  1838. // store the module definition for the last module in the chain
  1839. var moduleDefinitions = [];
  1840. moduleDefinitions[length-1] = moduleDefinition;
  1841. // Loop through all the parts of the module definition
  1842. _.each(moduleNames, function(moduleName, i){
  1843. var parentModule = module;
  1844. module = this._getModule(parentModule, moduleName, app);
  1845. this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
  1846. }, this);
  1847. // Return the last module in the definition chain
  1848. return module;
  1849. },
  1850. _getModule: function(parentModule, moduleName, app, def, args){
  1851. // Get an existing module of this name if we have one
  1852. var module = parentModule[moduleName];
  1853. if (!module){
  1854. // Create a new module if we don't have one
  1855. module = new Marionette.Module(moduleName, app);
  1856. parentModule[moduleName] = module;
  1857. // store the module on the parent
  1858. parentModule.submodules[moduleName] = module;
  1859. }
  1860. return module;
  1861. },
  1862. _addModuleDefinition: function(parentModule, module, def, args){
  1863. var fn;
  1864. var startWithParent;
  1865. if (_.isFunction(def)){
  1866. // if a function is supplied for the module definition
  1867. fn = def;
  1868. startWithParent = true;
  1869. } else if (_.isObject(def)){
  1870. // if an object is supplied
  1871. fn = def.define;
  1872. startWithParent = def.startWithParent;
  1873. } else {
  1874. // if nothing is supplied
  1875. startWithParent = true;
  1876. }
  1877. // add module definition if needed
  1878. if (fn){
  1879. module.addDefinition(fn, args);
  1880. }
  1881. // `and` the two together, ensuring a single `false` will prevent it
  1882. // from starting with the parent
  1883. module.startWithParent = module.startWithParent && startWithParent;
  1884. // setup auto-start if needed
  1885. if (module.startWithParent && !module.startWithParentIsConfigured){
  1886. // only configure this once
  1887. module.startWithParentIsConfigured = true;
  1888. // add the module initializer config
  1889. parentModule.addInitializer(function(options){
  1890. if (module.startWithParent){
  1891. module.start(options);
  1892. }
  1893. });
  1894. }
  1895. }
  1896. });
  1897. return Marionette;
  1898. })(this, Backbone, _);