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

/chapters/06-extensions.md

https://github.com/bbt123/backbone-fundamentals
Markdown | 1178 lines | 848 code | 330 blank | 0 comment | 0 complexity | 4625b7c8df867e8825ba2c40fea51aa6 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # Backbone Extensions
  2. Backbone is flexible, simple, and powerful. However, you may find that the complexity of the application you are working on requires more than what it provides out of the box. There are certain concerns which it just doesn't address directly as one of its goals is to be minimalist.
  3. Take for example Views, which provide a default `render` method which does nothing and produces no real results when called, despite most implementations using it to generate the HTML that the view manages. Also, Models and Collections have no built-in way of handling nested hierarchies - if you require this functionality, you need to write it yourself or use a plugin.
  4. In these cases, there are many existing Backbone plugins which can provide advanced solutions for large-scale Backbone apps. A fairly complete list of plugins and frameworks available can be found on the Backbone [wiki](https://github.com/documentcloud/backbone/wiki/Extensions%2C-Plugins%2C-Resources). Using these add-ons, there is enough for applications of most sizes to be completed successfully.
  5. In this section of the book we will look at two popular Backbone add-ons: MarionetteJS and Thorax.
  6. ## MarionetteJS (Backbone.Marionette)
  7. *By Derick Bailey & Addy Osmani*
  8. As we've seen, Backbone provides a great set of building blocks for our JavaScript applications. It gives us the core constructs that are needed to build small to mid-sized apps, organize jQuery DOM events, or create single page apps that support mobile devices and large scale enterprise needs. But Backbone is not a complete framework. It's a set of building blocks that leaves much of the application design, architecture, and scalability to the developer, including memory management, view management, and more.
  9. [MarionetteJS](http://marionettejs.com) (a.k.a. Backbone.Marionette) provides many of the features that the non-trivial application developer needs, above what Backbone itself provides. It is a composite application library that aims to simplify the construction of large scale applications. It does this by providing a collection of common design and implementation patterns found in the applications that the creator, [Derick Bailey](http://lostechies.com/derickbailey/), and many other [contributors](https://github.com/marionettejs/backbone.marionette/graphs/contributors) have been using to build Backbone apps.
  10. Marionette's key benefits include:
  11. * Scaling applications out with modular, event driven architecture
  12. * Sensible defaults, such as using Underscore templates for view rendering
  13. * Easy to modify to make it work with your application's specific needs
  14. * Reducing boilerplate for views, with specialized view types
  15. * Build on a modular architecture with an Application and modules that attach to it
  16. * Compose your application's visuals at runtime, with Region and Layout
  17. * Nested views and layouts within visual regions
  18. * Built-in memory management and zombie killing in views, regions, and layouts
  19. * Built-in event clean up with the EventBinder
  20. * Event-driven architecture with the EventAggregator
  21. * Flexible, "as-needed" architecture allowing you to pick and choose what you need
  22. * And much, much more
  23. Marionette follows a similar philosophy to Backbone in that it provides a suite of components that can be used independently of each other, or used together to create significant advantages for us as developers. But it steps above the structural components of Backbone and provides an application layer, with more than a dozen components and building blocks.
  24. Marionette's components range greatly in the features they provide, but they all work together to create a composite application layer that can both reduce boilerplate code and provide a much needed application structure. Its core components include various and specialized view types that take the boilerplate out of rendering common Backbone.Model and Backbone.Collection scenarios; an Application object and Module architecture to scale applications across sub-applications, features and files; integration of a command pattern, event aggregator, and request/response mechanism; and many more object types that can be extended in a myriad of ways to create an architecture that facilitates an application's specific needs.
  25. In spite of the large number of constructs that Marionette provides, though, you're not required to use all of it just because you want to use some of it. Much like Backbone itself, you can pick and choose which features you want to use and when. This allows you to work with other Backbone frameworks and plugins very easily. It also means that you are not required to engage in an all-or-nothing migration to begin using Marionette.
  26. ### Boilerplate Rendering Code
  27. Consider the code that it typically requires to render a view with Backbone and Underscore template. We need a template to render, which can be placed in the DOM directly, and we need the JavaScript that defines a view that uses the template and populates it with data from a model.
  28. ```
  29. <script type="text/html" id="my-view-template">
  30. <div class="row">
  31. <label>First Name:</label>
  32. <span><%= firstName %></span>
  33. </div>
  34. <div class="row">
  35. <label>Last Name:</label>
  36. <span><%= lastName %></span>
  37. </div>
  38. <div class="row">
  39. <label>Email:</label>
  40. <span><%= email %></span>
  41. </div>
  42. </script>
  43. ```
  44. ```javascript
  45. var MyView = Backbone.View.extend({
  46. template: $('#my-view-template').html(),
  47. render: function() {
  48. // compile the Underscore.js template
  49. var compiledTemplate = _.template(this.template);
  50. // render the template with the model data
  51. var data = _.clone(this.model.attributes);
  52. var html = compiledTemplate(data);
  53. // populate the view with the rendered html
  54. this.$el.html(html);
  55. }
  56. });
  57. ```
  58. Once this is in place, you need to create an instance of your view and pass your model into it. Then you can take the view's `el` and append it to the DOM in order to display the view.
  59. ```javascript
  60. var Derick = new Person({
  61. firstName: 'Derick',
  62. lastName: 'Bailey',
  63. email: 'derickbailey@example.com'
  64. });
  65. var myView = new MyView({
  66. model: Derick
  67. });
  68. myView.setElement("#content");
  69. myView.render();
  70. ```
  71. This is a standard set up for defining, building, rendering, and displaying a view with Backbone. This is also what we call "boilerplate code" - code that is repeated over and over and over again, across every project and every implementation with the same functionality. It gets to be tedious and repetitious very quickly.
  72. Enter Marionette's `ItemView` - a simple way to reduce the boilerplate of defining a view.
  73. ### Reducing Boilerplate With Marionette.ItemView
  74. All of Marionette's view types - with the exception of `Marionette.View` - include a built-in `render` method that handles the core rendering logic for you. We can take advantage of this by changing the `MyView` instance to inherit from one of these rather than `Backbone.View`. Instead of having to provide our own `render` method for the view, we can let Marionette render it for us. We'll still use the same Underscore.js template and rendering mechanism, but the implementation of this is hidden behind the scenes. Thus, we can reduce the amount of code needed for this view.
  75. ```javascript
  76. var MyView = Marionette.ItemView.extend({
  77. template: '#my-view-template'
  78. });
  79. ```
  80. And that's it - that's all you need to get the exact same behaviour as the previous view implementation. Just replace `Backbone.View.extend` with `Marionette.ItemView.extend`, then get rid of the `render` method. You can still create the view instance with a `model`, call the `render` method on the view instance, and display the view in the DOM the same way that we did before. But the view definition has been reduced to a single line of configuration for the template.
  81. ### Memory Management
  82. In addition to the reduction of code needed to define a view, Marionette includes some advanced memory management in all of its views, making the job of cleaning up a view instance and its event handlers easy.
  83. Consider the following view implementation:
  84. ```javascript
  85. var ZombieView = Backbone.View.extend({
  86. template: '#my-view-template',
  87. initialize: function() {
  88. // bind the model change to re-render this view
  89. this.model.on('change', this.render, this);
  90. },
  91. render: function() {
  92. // This alert is going to demonstrate a problem
  93. alert('We`re rendering the view');
  94. }
  95. });
  96. ```
  97. If we create two instances of this view using the same variable name for both instances, and then change a value in the model, how many times will we see the alert box?
  98. ```javascript
  99. var Person = Backbone.Model.extend({
  100. defaults: {
  101. "firstName": "Jeremy",
  102. "lastName": "Ashkenas",
  103. "email": "jeremy@example.com"
  104. }
  105. });
  106. var Derick = new Person({
  107. firstName: 'Derick',
  108. lastName: 'Bailey',
  109. email: 'derick@example.com'
  110. });
  111. // create the first view instance
  112. var zombieView = new ZombieView({
  113. model: Derick
  114. });
  115. // create a second view instance, re-using
  116. // the same variable name to store it
  117. zombieView = new ZombieView({
  118. model: Derick
  119. });
  120. Derick.set('email', 'derickbailey@example.com');
  121. ```
  122. Since we're re-using the same `zombieView` variable for both instances, the first instance of the view will fall out of scope immediately after the second is created. This allows the JavaScript garbage collector to come along and clean it up, which should mean the first view instance is no longer active and no longer going to respond to the model's "change" event.
  123. But when we run this code, we end up with the alert box showing up twice!
  124. The problem is caused by the model event binding in the view's `initialize` method. Whenever we pass `this.render` as the callback method to the model's `on` event binding, the model itself is being given a direct reference to the view instance. Since the model is now holding a reference to the view instance, replacing the `zombieView` variable with a new view instance is not going to let the original view fall out of scope. The model still has a reference, therefore the view is still in scope.
  125. Since the original view is still in scope, and the second view instance is also in scope, changing data on the model will cause both view instances to respond.
  126. Fixing this is easy, though. You just need to call `stopListening` when the view is done with its work and ready to be closed. To do this, add a `close` method to the view.
  127. ```javascript
  128. var ZombieView = Backbone.View.extend({
  129. template: '#my-view-template',
  130. initialize: function() {
  131. // bind the model change to re-render this view
  132. this.model.on('change', this.render, this);
  133. },
  134. close: function() {
  135. // unbind the events that this view is listening to
  136. this.stopListening();
  137. },
  138. render: function() {
  139. // This alert is going to demonstrate a problem
  140. alert('We`re rendering the view');
  141. }
  142. });
  143. ```
  144. Then call `close` on the first instance when it is no longer needed, and only one view instance will remain alive. For more information about the `listenTo` and `stopListening` functions, see the earlier Backbone Basics chapter and Derick's post on [Managing Events As Relationships, Not Just Resources](http://lostechies.com/derickbailey/2013/02/06/managing-events-as-relationships-not-just-references/).
  145. ```javascript
  146. var Jeremy = new Person({
  147. firstName: 'Jeremy',
  148. lastName: 'Ashkenas',
  149. email: 'jeremy@example.com'
  150. });
  151. // create the first view instance
  152. var zombieView = new ZombieView({
  153. model: Person
  154. })
  155. zombieView.close(); // double-tap the zombie
  156. // create a second view instance, re-using
  157. // the same variable name to store it
  158. zombieView = new ZombieView({
  159. model: Person
  160. })
  161. Person.set('email', 'jeremyashkenas@example.com');
  162. ```
  163. Now we only see one alert box when this code runs.
  164. Rather than having to manually remove these event handlers, though, we can let Marionette do it for us.
  165. ```javascript
  166. var ZombieView = Marionette.ItemView.extend({
  167. template: '#my-view-template',
  168. initialize: function() {
  169. // bind the model change to re-render this view
  170. this.listenTo(this.model, 'change', this.render);
  171. },
  172. render: function() {
  173. // This alert is going to demonstrate a problem
  174. alert('We`re rendering the view');
  175. }
  176. });
  177. ```
  178. Notice in this case we are using a method called `listenTo`. This method comes from Backbone.Events, and is available in all objects that mix in Backbone.Events - including most Marionette objects. The `listenTo` method signature is similar to that of the `on` method, with the exception of passing the object that triggers the event as the first parameter.
  179. Marionette's views also provide a `close` event, in which the event bindings that are set up with the `listenTo` are automatically removed. This means we no longer need to define a `close` method directly, and when we use the `listenTo` method, we know that our events will be removed and our views will not turn into zombies.
  180. But how do we automate the call to `close` on a view, in the real application? When and where do we call that? Enter the `Marionette.Region` - an object that manages the lifecycle of an individual view.
  181. ### Region Management
  182. After a view is created, it typically needs to be placed in the DOM so that it becomes visible. This is usually done with a jQuery selector and setting the `html()` of the resulting object:
  183. ```javascript
  184. var Joe = new Person({
  185. firstName: 'Joe',
  186. lastName: 'Bob',
  187. email: 'joebob@example.com'
  188. });
  189. var myView = new MyView({
  190. model: Joe
  191. })
  192. myView.render();
  193. // show the view in the DOM
  194. $('#content').html(myView.el)
  195. ```
  196. This, again, is boilerplate code. We shouldn't have to manually call `render` and manually select the DOM elements to show the view. Furthermore, this code doesn't lend itself to closing any previous view instance that might be attached to the DOM element we want to populate. And we've seen the danger of zombie views already.
  197. To solve these problems, Marionette provides a `Region` object - an object that manages the lifecycle of individual views, displayed in a particular DOM element.
  198. ```javascript
  199. // create a region instance, telling it which DOM element to manage
  200. var myRegion = new Marionette.Region({
  201. el: '#content'
  202. });
  203. // show a view in the region
  204. var view1 = new MyView({ /* ... */ });
  205. myRegion.show(view1);
  206. // somewhere else in the code,
  207. // show a different view
  208. var view2 = new MyView({ /* ... */ });
  209. myRegion.show(view2);
  210. ```
  211. There are several things to note, here. First, we're telling the region what DOM element to manage by specifying an `el` in the region instance. Second, we're no longer calling the `render` method on our views. And lastly, we're not calling `close` on our view, either, though this is getting called for us.
  212. When we use a region to manage the lifecycle of our views, and display the views in the DOM, the region itself handles these concerns. By passing a view instance into the `show` method of the region, it will call the render method on the view for us. It will then take the resulting `el` of the view and populate the DOM element.
  213. The next time we call the `show` method of the region, the region remembers that it is currently displaying a view. The region calls the `close` method on the view, removes it from the DOM, and then proceeds to run the render & display code for the new view that was passed in.
  214. Since the region handles calling `close` for us, and we're using the `listenTo` event binder in our view instance, we no longer have to worry about zombie views in our application.
  215. Regions are not limited to just Marionette views, though. Any valid Backbone.View can be managed by a Marionette.Region. If your view happens to have a `close` method, it will be called when the view is closed. If not, the Backbone.View built-in method, `remove`, will be called instead.
  216. ### Marionette Todo app
  217. Having learned about Marionette's high-level concepts, let's explore refactoring the Todo application we created in our first exercise to use it. The complete code for this application can be found in Derick's TodoMVC [fork](https://github.com/derickbailey/todomvc/tree/marionette/labs/architecture-examples/backbone_marionette/js).
  218. Our final implementation will be visually and functionally equivalent to the original app, as seen below.
  219. ![](img/marionette_todo0.png)
  220. First, we define an application object representing our base TodoMVC app. This will contain initialization code and define the default layout regions for our app.
  221. **TodoMVC.js:**
  222. ```javascript
  223. var TodoMVC = new Backbone.Marionette.Application();
  224. TodoMVC.addRegions({
  225. header: '#header',
  226. main: '#main',
  227. footer: '#footer'
  228. });
  229. TodoMVC.on('initialize:after', function() {
  230. Backbone.history.start();
  231. });
  232. ```
  233. Regions are used to manage the content that's displayed within specific elements, and the `addRegions` method on the `TodoMVC` object is just a shortcut for creating `Region` objects. We supply a jQuery selector for each region to manage (e.g., `#header`, `#main`, and `#footer`) and then tell the region to show various Backbone views within that region.
  234. Once the application object has been initialized, we call `Backbone.history.start()` to route the initial URL.
  235. Next, we define our Layouts. A layout is a specialized type of view that directly extends `Marionette.ItemView`. This means it's intended to render a single template and may or may not have a model (or `item`) associated with the template.
  236. One of the main differences between a Layout and an `ItemView` is that the layout contains regions. When defining a Layout, we supply it with both a `template` and the regions that the template contains. After rendering the layout, we can display other views within the layout using the regions that were defined.
  237. In our TodoMVC Layout module below, we define Layouts for:
  238. * Header: where we can create new Todos
  239. * Footer: where we summarize how many Todos are remaining/have been completed
  240. This captures some of the view logic that was previously in our `AppView` and `TodoView`.
  241. Note that Marionette modules (such as the below) offer a simple module system which is used to create privacy and encapsulation in Marionette apps. These certainly don't have to be used however, and later on in this section we'll provide links to alternative implementations using RequireJS + AMD instead.
  242. **TodoMVC.Layout.js:**
  243. ```javascript
  244. TodoMVC.module('Layout', function(Layout, App, Backbone, Marionette, $, _) {
  245. // Layout Header View
  246. // ------------------
  247. Layout.Header = Backbone.Marionette.ItemView.extend({
  248. template: '#template-header',
  249. // UI Bindings create cached attributes that
  250. // point to jQuery selected objects.
  251. ui: {
  252. input: '#new-todo'
  253. },
  254. events: {
  255. 'keypress #new-todo': 'onInputKeypress',
  256. 'blur #new-todo': 'onTodoBlur'
  257. },
  258. onTodoBlur: function(){
  259. var todoText = this.ui.input.val().trim();
  260. this.createTodo(todoText);
  261. },
  262. onInputKeypress: function(e) {
  263. var ENTER_KEY = 13;
  264. var todoText = this.ui.input.val().trim();
  265. if ( e.which === ENTER_KEY && todoText ) {
  266. this.createTodo(todoText);
  267. }
  268. },
  269. completeAdd: function() {
  270. this.ui.input.val('');
  271. },
  272. createTodo: function(todoText) {
  273. if (todoText.trim() === ""){ return; }
  274. this.collection.create({
  275. title: todoText
  276. });
  277. this.completeAdd();
  278. }
  279. });
  280. // Layout Footer View
  281. // ------------------
  282. Layout.Footer = Marionette.Layout.extend({
  283. template: '#template-footer',
  284. // UI Bindings create cached attributes that
  285. // point to jQuery selected objects.
  286. ui: {
  287. todoCount: '#todo-count .count',
  288. todoCountLabel: '#todo-count .label',
  289. clearCount: '#clear-completed .count',
  290. filters: "#filters a"
  291. },
  292. events: {
  293. "click #clear-completed": "onClearClick"
  294. },
  295. initialize: function() {
  296. this.bindTo( App.vent, "todoList: filter", this.updateFilterSelection, this );
  297. this.bindTo( this.collection, 'all', this.updateCount, this );
  298. },
  299. onRender: function() {
  300. this.updateCount();
  301. },
  302. updateCount: function() {
  303. var activeCount = this.collection.getActive().length,
  304. completedCount = this.collection.getCompleted().length;
  305. this.ui.todoCount.html(activeCount);
  306. this.ui.todoCountLabel.html(activeCount === 1 ? 'item' : 'items');
  307. this.ui.clearCount.html(completedCount === 0 ? '' : '(' + completedCount + ')');
  308. },
  309. updateFilterSelection: function( filter ) {
  310. this.ui.filters
  311. .removeClass('selected')
  312. .filter( '[href="#' + filter + '"]')
  313. .addClass( 'selected' );
  314. },
  315. onClearClick: function() {
  316. var completed = this.collection.getCompleted();
  317. completed.forEach(function destroy(todo) {
  318. todo.destroy();
  319. });
  320. }
  321. });
  322. });
  323. ```
  324. Next, we tackle application routing and workflow, such as controlling Layouts in the page which can be shown or hidden.
  325. Recall how Backbone routes trigger methods within the Router as shown below in our original Workspace router from our first exercise:
  326. ```javascript
  327. var Workspace = Backbone.Router.extend({
  328. routes: {
  329. '*filter': 'setFilter'
  330. },
  331. setFilter: function(param) {
  332. // Set the current filter to be used
  333. window.app.TodoFilter = param.trim() || '';
  334. // Trigger a collection filter event, causing hiding/unhiding
  335. // of Todo view items
  336. window.app.Todos.trigger('filter');
  337. }
  338. });
  339. ```
  340. Marionette uses the concept of an AppRouter to simplify routing. This reduces the boilerplate for handling route events and allows routers to be configured to call methods on an object directly. We configure our AppRouter using `appRoutes` which replaces the `'*filter': 'setFilter'` route defined in our original router and invokes a method on our Controller.
  341. The TodoList Controller, also found in this next code block, handles some of the remaining visibility logic originally found in `AppView` and `TodoView`, albeit using very readable Layouts.
  342. **TodoMVC.TodoList.js:**
  343. ```javascript
  344. TodoMVC.module('TodoList', function(TodoList, App, Backbone, Marionette, $, _) {
  345. // TodoList Router
  346. // ---------------
  347. //
  348. // Handle routes to show the active vs complete todo items
  349. TodoList.Router = Marionette.AppRouter.extend({
  350. appRoutes: {
  351. '*filter': 'filterItems'
  352. }
  353. });
  354. // TodoList Controller (Mediator)
  355. // ------------------------------
  356. //
  357. // Control the workflow and logic that exists at the application
  358. // level, above the implementation detail of views and models
  359. TodoList.Controller = function() {
  360. this.todoList = new App.Todos.TodoList();
  361. };
  362. _.extend(TodoList.Controller.prototype, {
  363. // Start the app by showing the appropriate views
  364. // and fetching the list of todo items, if there are any
  365. start: function() {
  366. this.showHeader(this.todoList);
  367. this.showFooter(this.todoList);
  368. this.showTodoList(this.todoList);
  369. App.bindTo(this.todoList, 'reset add remove', this.toggleFooter, this);
  370. this.todoList.fetch();
  371. },
  372. showHeader: function(todoList) {
  373. var header = new App.Layout.Header({
  374. collection: todoList
  375. });
  376. App.header.show(header);
  377. },
  378. showFooter: function(todoList) {
  379. var footer = new App.Layout.Footer({
  380. collection: todoList
  381. });
  382. App.footer.show(footer);
  383. },
  384. showTodoList: function(todoList) {
  385. App.main.show(new TodoList.Views.ListView({
  386. collection: todoList
  387. }));
  388. },
  389. toggleFooter: function() {
  390. App.footer.$el.toggle(this.todoList.length);
  391. },
  392. // Set the filter to show complete or all items
  393. filterItems: function(filter) {
  394. App.vent.trigger('todoList:filter', filter.trim() || '');
  395. }
  396. });
  397. // TodoList Initializer
  398. // --------------------
  399. //
  400. // Get the TodoList up and running by initializing the mediator
  401. // when the the application is started, pulling in all of the
  402. // existing Todo items and displaying them.
  403. TodoList.addInitializer(function() {
  404. var controller = new TodoList.Controller();
  405. new TodoList.Router({
  406. controller: controller
  407. });
  408. controller.start();
  409. });
  410. });
  411. ```
  412. ####Controllers
  413. In this particular app, note that Controllers don't add a great deal to the overall workflow. In general, Marionette's philosophy on routers is that they should be an afterthought in the implementation of applications. Quite often, we've seen developers abuse Backbone's routing system by making it the sole controller of the entire application workflow and logic.
  414. This inevitably leads to mashing every possible combination of code into the router methods - view creation, model loading, coordinating different parts of the app, etc. Developers such as Derick view this as a violation of the [single-responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle) (SRP) and separation of concerns.
  415. Backbone's router and history exist to deal with a specific aspect of browsers - managing the forward and back buttons. Marionette's philosophy is that it should be limited to that, with the code that gets executed by the navigation being somewhere else. This allows the application to be used with or without a router. We can call a controller's "show" method from a button click, from an application event handler, or from a router, and we will end up with the same application state no matter how we called that method.
  416. Derick has written extensively about his thoughts on this topic, which you can read more about on his blog:
  417. * [http://lostechies.com/derickbailey/2011/12/27/the-responsibilities-of-the-various-pieces-of-backbone-js/](http://lostechies.com/derickbailey/2011/12/27/the-responsibilities-of-the-various-pieces-of-backbone-js/)
  418. * [http://lostechies.com/derickbailey/2012/01/02/reducing-backbone-routers-to-nothing-more-than-configuration/](http://lostechies.com/derickbailey/2012/01/02/reducing-backbone-routers-to-nothing-more-than-configuration/)
  419. * [http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/](http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/)
  420. #### CompositeView
  421. Our next task is defining the actual views for individual Todo items and lists of items in our TodoMVC application. For this, we make use of Marionette's `CompositeView`s. The idea behind a CompositeView is that it represents a visualization of a composite or hierarchical structure of leaves (or nodes) and branches.
  422. Think of these views as being a hierarchy of parent-child models, and recursive by default. The same CompositeView type will be used to render each item in a collection that is handled by the composite view. For non-recursive hierarchies, we are able to override the item view by defining an `itemView` attribute.
  423. For our Todo List Item View, we define it as an ItemView, then our Todo List View is a CompositeView where we override the `itemView` setting and tell it to use the Todo List Item View for each item in the collection.
  424. TodoMVC.TodoList.Views.js
  425. ```javascript
  426. TodoMVC.module('TodoList.Views', function(Views, App, Backbone, Marionette, $, _) {
  427. // Todo List Item View
  428. // -------------------
  429. //
  430. // Display an individual todo item, and respond to changes
  431. // that are made to the item, including marking completed.
  432. Views.ItemView = Marionette.ItemView.extend({
  433. tagName: 'li',
  434. template: '#template-todoItemView',
  435. ui: {
  436. edit: '.edit'
  437. },
  438. events: {
  439. 'click .destroy': 'destroy',
  440. 'dblclick label': 'onEditClick',
  441. 'keypress .edit': 'onEditKeypress',
  442. 'blur .edit' : 'onEditBlur',
  443. 'click .toggle' : 'toggle'
  444. },
  445. initialize: function() {
  446. this.bindTo(this.model, 'change', this.render, this);
  447. },
  448. onRender: function() {
  449. this.$el.removeClass( 'active completed' );
  450. if ( this.model.get( 'completed' )) {
  451. this.$el.addClass( 'completed' );
  452. } else {
  453. this.$el.addClass( 'active' );
  454. }
  455. },
  456. destroy: function() {
  457. this.model.destroy();
  458. },
  459. toggle: function() {
  460. this.model.toggle().save();
  461. },
  462. onEditClick: function() {
  463. this.$el.addClass('editing');
  464. this.ui.edit.focus();
  465. },
  466. updateTodo : function() {
  467. var todoText = this.ui.edit.val();
  468. if (todoText === '') {
  469. return this.destroy();
  470. }
  471. this.setTodoText(todoText);
  472. this.completeEdit();
  473. },
  474. onEditBlur: function(e){
  475. this.updateTodo();
  476. },
  477. onEditKeypress: function(e) {
  478. var ENTER_KEY = 13;
  479. var todoText = this.ui.edit.val().trim();
  480. if ( e.which === ENTER_KEY && todoText ) {
  481. this.model.set('title', todoText).save();
  482. this.$el.removeClass('editing');
  483. }
  484. },
  485. setTodoText: function(todoText){
  486. if (todoText.trim() === ""){ return; }
  487. this.model.set('title', todoText).save();
  488. },
  489. completeEdit: function(){
  490. this.$el.removeClass('editing');
  491. }
  492. });
  493. // Item List View
  494. // --------------
  495. //
  496. // Controls the rendering of the list of items, including the
  497. // filtering of active vs completed items for display.
  498. Views.ListView = Backbone.Marionette.CompositeView.extend({
  499. template: '#template-todoListCompositeView',
  500. itemView: Views.ItemView,
  501. itemViewContainer: '#todo-list',
  502. ui: {
  503. toggle: '#toggle-all'
  504. },
  505. events: {
  506. 'click #toggle-all': 'onToggleAllClick'
  507. },
  508. initialize: function() {
  509. this.bindTo(this.collection, 'all', this.update, this);
  510. },
  511. onRender: function() {
  512. this.update();
  513. },
  514. update: function() {
  515. function reduceCompleted(left, right) {
  516. return left && right.get('completed');
  517. }
  518. var allCompleted = this.collection.reduce(reduceCompleted,true);
  519. this.ui.toggle.prop('checked', allCompleted);
  520. this.$el.parent().toggle(!!this.collection.length);
  521. },
  522. onToggleAllClick: function(e) {
  523. var isChecked = e.currentTarget.checked;
  524. this.collection.each(function(todo) {
  525. todo.save({'completed': isChecked});
  526. });
  527. }
  528. });
  529. // Application Event Handlers
  530. // --------------------------
  531. //
  532. // Handler for filtering the list of items by showing and
  533. // hiding through the use of various CSS classes
  534. App.vent.on('todoList:filter',function(filter) {
  535. filter = filter || 'all';
  536. $('#todoapp').attr('class', 'filter-' + filter);
  537. });
  538. });
  539. ```
  540. At the end of the last code block, you will also notice an event handler using `vent`. This is an event aggregator that allows us to handle `filterItem` triggers from our TodoList controller.
  541. Finally, we define the model and collection for representing our Todo items. These are semantically not very different from the original versions we used in our first exercise and have been re-written to better fit in with Derick's preferred style of coding.
  542. **TodoMVC.Todos.js:**
  543. ```javascript
  544. TodoMVC.module('Todos', function(Todos, App, Backbone, Marionette, $, _) {
  545. // Local Variables
  546. // ---------------
  547. var localStorageKey = 'todos-backbone-marionettejs';
  548. // Todo Model
  549. // ----------
  550. Todos.Todo = Backbone.Model.extend({
  551. localStorage: new Backbone.LocalStorage(localStorageKey),
  552. defaults: {
  553. title: '',
  554. completed: false,
  555. created: 0
  556. },
  557. initialize: function() {
  558. if (this.isNew()) {
  559. this.set('created', Date.now());
  560. }
  561. },
  562. toggle: function() {
  563. return this.set('completed', !this.isCompleted());
  564. },
  565. isCompleted: function() {
  566. return this.get('completed');
  567. }
  568. });
  569. // Todo Collection
  570. // ---------------
  571. Todos.TodoList = Backbone.Collection.extend({
  572. model: Todos.Todo,
  573. localStorage: new Backbone.LocalStorage(localStorageKey),
  574. getCompleted: function() {
  575. return this.filter(this._isCompleted);
  576. },
  577. getActive: function() {
  578. return this.reject(this._isCompleted);
  579. },
  580. comparator: function(todo) {
  581. return todo.get('created');
  582. },
  583. _isCompleted: function(todo) {
  584. return todo.isCompleted();
  585. }
  586. });
  587. });
  588. ```
  589. We finally kick-start everything off in our application index file, by calling `start` on our main application object:
  590. Initialization:
  591. ```javascript
  592. $(function() {
  593. // Start the TodoMVC app (defined in js/TodoMVC.js)
  594. TodoMVC.start();
  595. });
  596. ```
  597. And that's it!
  598. ### Is the Marionette implementation of the Todo app more maintainable?
  599. Derick feels that maintainability largely comes down to modularity, separating responsibilities (Single Responsibility Principle and Separation of Concerns) by using patterns to keep concerns from being mixed together. It can, however, be difficult to simply extract things into separate modules for the sake of extraction, abstraction, or dividing the concept down into its simplest parts.
  600. The Single Responsibility Principle (SRP) tells us quite the opposite - that we need to understand the context in which things change. What parts always change together, in _this_ system? What parts can change independently? Without knowing this, we won't know what pieces should be broken out into separate components and modules versus put together into the same module or object.
  601. The way Derick organizes his apps into modules is by creating a breakdown of concepts at each level. A higher level module is a higher level of concern - an aggregation of responsibilities. Each responsibility is broken down into an expressive API set that is implemented by lower level modules (Dependency Inversion Principle). These are coordinated through a mediator - which he typically refers to as the Controller in a module.
  602. The way Derick organizes his files also plays directly into maintainability and he has also written posts about the importance of keeping a sane application folder structure that I recommend reading:
  603. * [http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/](http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/)
  604. * [http://hilojs.codeplex.com/discussions/362875#post869640](http://hilojs.codeplex.com/discussions/362875#post869640)
  605. ### Marionette And Flexibility
  606. Marionette is a flexible framework, much like Backbone itself. It offers a wide variety of tools to help create and organize an application architecture on top of Backbone, but like Backbone itself, it doesn't dictate that you have to use all of its pieces in order to use any of them.
  607. The flexibility and versatility in Marionette is easiest to understand by examining three variations of TodoMVC implemented with it that have been created for comparison purposes:
  608. * [Simple](https://github.com/jsoverson/todomvc/tree/master/labs/architecture-examples/backbone_marionette) - by Jarrod Overson
  609. * [RequireJS](https://github.com/jsoverson/todomvc/tree/master/labs/dependency-examples/backbone_marionette_require) - also by Jarrod
  610. * [Marionette modules](https://github.com/derickbailey/todomvc/tree/marionette/labs/architecture-examples/backbone_marionette/js) - by Derick Bailey
  611. **The simple version**: This version of TodoMVC shows some raw use of Marionette's various view types, an application object, and the event aggregator. The objects that are created are added directly to the global namespace and are fairly straightforward. This is a great example of how Marionette can be used to augment existing code without having to re-write everything around Marionette.
  612. **The RequireJS version**: Using Marionette with RequireJS helps to create a modularized application architecture - a tremendously important concept in scaling JavaScript applications. RequireJS provides a powerful set of tools that can be leveraged to great advantage, making Marionette even more flexible than it already is.
  613. **The Marionette module version**: RequireJS isn't the only way to create a modularized application architecture, though. For those that wish to build applications in modules and namespaces, Marionette provides a built-in module and namespacing structure. This example application takes the simple version of the application and re-writes it into a namespaced application architecture, with an application controller (mediator / workflow object) that brings all of the pieces together.
  614. Marionette certainly provides its share of opinions on how a Backbone application should be architected. The combination of modules, view types, event aggregator, application objects, and more, can be used to create a very powerful and flexible architecture based on these opinions.
  615. But as you can see, Marionette isn't a completely rigid, "my way or the highway" framework. It provides many elements of an application foundation that can be mixed and matched with other architectural styles, such as AMD or namespacing, or provide simple augmentation to existing projects by reducing boilerplate code for rendering views.
  616. This flexibility creates a much greater opportunity for Marionette to provide value to you and your projects, as it allows you to scale the use of Marionette with your application's needs.
  617. ### And So Much More
  618. This is just the tip of the proverbial iceberg for Marionette, even for the `ItemView` and `Region` objects that we've explored. There is far more functionality, more features, and more flexibility and customizability that can be put to use in both of these objects. Then we have the other dozen or so components that Marionette provides, each with their own set of behaviors built in, customization and extension points, and more.
  619. To learn more about Marionette's components, the features they provide and how to use them, check out the Marionette documentation, links to the wiki, to the source code, the project core contributors, and much more at [http://marionettejs.com](http://marionettejs.com).
  620. <p>&nbsp;</p>
  621. <p>&nbsp;</p>
  622. ## Thorax
  623. *By Ryan Eastridge & Addy Osmani*
  624. Part of Backbone's appeal is that it provides structure but is generally un-opinionated, in particular when it comes to views. Thorax makes an opinionated decision to use Handlebars as its templating solution. Some of the patterns found in Marionette are found in Thorax as well. Marionette exposes most of these patterns as JavaScript APIs while in Thorax they are often exposed as template helpers. This chapter assumes the reader has knowledge of Handlebars.
  625. Thorax was created by Ryan Eastridge and Kevin Decker to create Walmart's mobile web application. This chapter is limited to Thorax's templating features and patterns implemented in Thorax that you can utilize in your application regardless of whether you choose to adopt Thorax. To learn more about other features implemented in Thorax and to download boilerplate projects visit the [Thorax website](http://thoraxjs.org).
  626. ### Hello World
  627. In Backbone, when creating a new view, options passed are merged into any default options already present on a view and are exposed via `this.options` for later reference.
  628. `Thorax.View` differs from `Backbone.View` in that there is no `options` object. All arguments passed to the constructor become properties of the view, which in turn become available to the `template`:
  629. ```javascript
  630. var view = new Thorax.View({
  631. greeting: 'Hello',
  632. template: Handlebars.compile('{{greeting}} World!')
  633. });
  634. view.appendTo('body');
  635. ```
  636. In most examples in this chapter a `template` property will be specified. In larger projects including the boilerplate projects provided on the Thorax website a `name` property would instead be used and a `template` of the same file name in your project would automatically be assigned to the view.
  637. If a `model` is set on a view, its attributes also become available to the template:
  638. var view = new Thorax.View({
  639. model: new Thorax.Model({key: 'value'}),
  640. template: Handlebars.compile('{{key}}')
  641. });
  642. ### Embedding child views
  643. The view helper allows you to embed other views within a view. Child views can be specified as properties of the view:
  644. ```javascript
  645. var parent = new Thorax.View({
  646. child: new Thorax.View(...),
  647. template: Handlebars.compile('{{view child}}')
  648. });
  649. ```
  650. Or the name of a child view to initialize as well as any optional properties you wish to pass. In this case the child view must have previously been created with `extend` and given a `name` property:
  651. ```javascript
  652. var ChildView = Thorax.View.extend({
  653. name: 'child',
  654. template: ...
  655. });
  656. var parent = new Thorax.View({
  657. template: Handlebars.compile('{{view "child" key="value"}}')
  658. });
  659. ```
  660. The view helper may also be used as a block helper, in which case the block will be assigned as the `template` property of the child view:
  661. ```handlebars
  662. {{#view child}}
  663. child will have this block
  664. set as its template property
  665. {{/view}}
  666. ```
  667. Handlebars is string based, while `Backbone.View` instances have a DOM `el`. Since we are mixing metaphors, the embedding of views works via a placeholder mechanism where the `view` helper in this case adds the view passed to the helper to a hash of `children`, then injects placeholder HTML into the template such as:
  668. ```html
  669. <div data-view-placeholder-cid="view2"></div>
  670. ```
  671. Then once the parent view is rendered, we walk the DOM in search of all the placeholders we created, replacing them with the child views' `el`s:
  672. ```javascript
  673. this.$el.find('[data-view-placeholder-cid]').forEach(function(el) {
  674. var cid = el.getAttribute('data-view-placeholder-cid'),
  675. view = this.children[cid];
  676. view.render();
  677. $(el).replaceWith(view.el);
  678. }, this);
  679. ```
  680. ### View helpers
  681. One of the most useful constructs in Thorax is `Handlebars.registerViewHelper` (not to be confused with `Handlebars.registerHelper`). This method will register a new block helper that will create and embed a `HelperView` instance with its `template` set to the captured block. A `HelperView` instance is different from that of a regular child view in that its context will be that of the parent's in the template. Like other child views it will have a `parent` property set to that of the declaring view. Many of the built-in helpers in Thorax including the `collection` helper are created in this manner.
  682. A simple example would be an `on` helper that re-rendered the generated `HelperView` instance each time an event was triggered on the declaring / parent view:
  683. Handlebars.registerViewHelper('on', function(eventName, helperView) {
  684. helperView.parent.on(eventName, function() {
  685. helperView.render();
  686. });
  687. });
  688. An example use of this would be to have a counter that would increment each time a button was clicked. This example makes use of the `button` helper in Thorax which simply makes a button that triggers a view event when clicked:
  689. ```handlebars
  690. {{#on "incremented"}}{{i}}{{/on}}
  691. {{#button trigger="incremented"}}Add{{/button}}
  692. ```
  693. And the corresponding view class:
  694. ```javascript
  695. new Thorax.View({
  696. events: {
  697. incremented: function() {
  698. ++this.i;
  699. }
  700. },
  701. initialize: function() {
  702. this.i = 0;
  703. },
  704. template: ...
  705. });
  706. ```
  707. ### collection helper
  708. The `collection` helper creates and embeds a `CollectionView` instance, creating a view for each item in a collection, updating when items are added, removed, or changed in the collection. The simplest usage of the helper would look like:
  709. ```handlebars
  710. {{#collection kittens}}
  711. <li>{{name}}</li>
  712. {{/collection}}
  713. ```
  714. And the corresponding view:
  715. ```javascript
  716. new Thorax.View({
  717. kittens: new Thorax.Collection(...),
  718. template: ...
  719. });
  720. ```
  721. The block in this case will be assigned as the `template` for each item view created, and the context will be the `attributes` of the given model. This helper accepts options that can be arbitrary HTML attributes, a `tag` option to specify the type of tag containing the collection, or any of the following:
  722. - `item-template` - A template to display for each model. If a block is specified it will become the item-template
  723. - `item-view` - A view class to use when each item view is created
  724. - `empty-template` - A template to display when the collection is empty. If an inverse / else block is specified it will become the empty-template
  725. - `empty-view` - A view to display when the collection is empty
  726. Options and blocks can be used in combination, in this case creating a `KittenView` class with a `template` set to the captured block for each kitten in the collection:
  727. ```handlebars
  728. {{#collection kittens item-view="KittenView" tag="ul"}}
  729. <li>{{name}}</li>
  730. {{else}}
  731. <li>No kittens!</li>
  732. {{/collection}}
  733. ```
  734. Note that multiple collections can be used per view, and collections can be nested. This is useful when there are models that contain collections that contain models that contain...
  735. ```handlebars
  736. {{#collection kittens}}
  737. <h2>{{name}}</h2>
  738. <p>Kills:</p>
  739. {{#collection miceKilled tag="ul"}}
  740. <li>{{name}}</li>
  741. {{/collection}}
  742. {{/collection}}
  743. ```
  744. ### Custom HTML data attributes
  745. Thorax makes heavy use of custom HTML data attributes to operate. While some make sense only within the context of Thorax, several are quite useful to have in any Backbone project for writing other functions against, or for general debugging. In order to add some to your views in non-Thorax projects, override the `setElement` method in your base view class:
  746. ```javascript
  747. MyApplication.View = Backbone.View.extend({
  748. setElement: function() {
  749. var response = Backbone.View.prototype.setElement.apply(this, arguments);
  750. this.name && this.$el.attr('data-view-name', this.name);
  751. this.$el.attr('data-view-cid', this.cid);
  752. this.collection && this.$el.attr('data-collection-cid', this.collection.cid);
  753. this.model && this.$el.attr('data-model-cid', this.model.cid);
  754. return response;
  755. }
  756. });
  757. ```
  758. In addition to making your application more immediately comprehensible in the inspector, it's now possible to extend jQuery / Zepto with functions to lookup the closest view, model or collection to a given element. In order to make it work you have to save references to each view created in your base view class by overriding the `_configure` method:
  759. ```javascript
  760. MyApplication.View = Backbone.View.extend({
  761. _configure: function() {
  762. Backbone.View.prototype._configure.apply(this, arguments);
  763. Thorax._viewsIndexedByCid[this.cid] = this;
  764. },
  765. dispose: function() {
  766. Backbone.View.prototype.dispose.apply(this, arguments);
  767. delete Thorax._viewsIndexedByCid[this.cid];
  768. }
  769. });
  770. ```
  771. Then we can extend jQuery / Zepto:
  772. ```javascript
  773. $.fn.view = function() {
  774. var el = $(this).closest('[data-view-cid]');
  775. return el && Thorax._viewsIndexedByCid[el.attr('data-view-cid')];
  776. };
  777. $.fn.model = function(view) {
  778. var $this = $(this),
  779. modelElement = $this.closest('[data-model-cid]'),
  780. modelCid = modelElement && modelElement.attr('[data-model-cid]');
  781. if (modelCid) {
  782. var view = $this.view();
  783. return view && view.model;
  784. }
  785. return false;
  786. };
  787. ```
  788. Now instead of storing references to models randomly throughout your application to lookup when a given DOM event occurs you can use `$(element).model()`. In Thorax, this can particularly useful in conjunction with the `collection` helper which generates a view class (with a `model` property) for each `model` in the collection. An example template:
  789. ```handlebars
  790. {{#collection kittens tag="ul"}}
  791. <li>{{name}}</li>
  792. {{/collection}}
  793. ```
  794. And the corresponding view class:
  795. ```javascript
  796. Thorax.View.extend({
  797. events: {
  798. 'click li': function(event) {
  799. var kitten = $(event.target).model();
  800. console.log('Clicked on ' + kitten.get('name'));
  801. }
  802. },
  803. kittens: new Thorax.Collection(...),
  804. template: ...
  805. });
  806. ```
  807. A common anti-pattern in Backbone applications is to assign a `className` to a single view class. Consider using the `data-view-name` attribute as a CSS selector instead, saving CSS classes for things that will be used multiple times:
  808. ```css
  809. [data-view-name="child"] {
  810. }
  811. ```
  812. ### Thorax Resources
  813. No Backbone related tutorial would be complete without a todo application. A [Thorax implementation of TodoMVC](http://todomvc.com/labs/architecture-examples/thorax/) is available, in addition to this far simpler example composed of this single Handlebars template:
  814. ```handlebars
  815. {{#collection todos tag="ul"}}
  816. <li{{#if done}} class="done"{{/if}}>
  817. <input type="checkbox" name="done"{{#if done}} checked="checked"{{/if}}>
  818. <span>{{item}}</span>
  819. </li>
  820. {{/collection}}
  821. <form>
  822. <input type="text">
  823. <input type="submit" value="Add">
  824. </form>
  825. ```
  826. and the corresponding JavaScript:
  827. ```javascript
  828. var todosView = Thorax.View({
  829. todos: new Thorax.Collection(),
  830. events: {
  831. 'change input[type="checkbox"]': function(event) {
  832. var target = $(event.target);
  833. target.model().set({done: !!target.attr('checked')});
  834. },
  835. 'submit form': function(event) {
  836. event.preventDefault();
  837. var input = this.$('input[type="text"]');
  838. this.todos.add({item: i

Large files files are truncated, but you can click here to view the full file