PageRenderTime 71ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/index.md

https://github.com/timothywebster/backbone-fundamentals
Markdown | 5992 lines | 4136 code | 1856 blank | 0 comment | 0 complexity | b4882a0c88331a1b332229578a60ef64 MD5 | raw file

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

  1. ##Prelude
  2. Welcome to my (in-progress) book about the [Backbone.js](http://documentcloud.github.com/backbone/) framework for structuring JavaScript applications. It's released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported [license](http://creativecommons.org/licenses/by-nc-sa/3.0/) meaning you can both grab a copy of the book for free or help to further [improve](https://github.com/addyosmani/backbone-fundamentals/) it.
  3. I'm very pleased to announce that this book will be out in physical form in a few months time via [O'Reilly Media](http://oreilly.com). Readers will have the option of purchasing the latest version in either print or a number of digital formats then or can grab a recent version from this repository.
  4. Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help.
  5. My extended thanks go out to [Jeremy Ashkenas](https://github.com/jashkenas) for creating Backbone.js and [these](https://github.com/addyosmani/backbone-fundamentals/contributors) members of the community for their assistance tweaking this project.
  6. I hope you find this book helpful!
  7. ##Table Of Contents
  8. * ####[Introduction](#introduction)
  9. * ####[Fundamentals](#fundamentals)
  10. * [MVC, MVP & Backbone.js](#mvc-mvp)
  11. * ####[The Basics](#thebasics)
  12. * [Models](#models)
  13. * [Views](#views)
  14. * [Collections](#collections)
  15. * [Routers](#routers)
  16. * [Namespacing](#namespacing)
  17. * [Additional tips](#additional-tips)
  18. * ####[RESTful Applications](#restfulapps)
  19. * [Building RESTful applications with Backbone](#restful)
  20. * [Building Backbone apps with Node.js, Express, Mongoose and MongoDB](#stack1)
  21. * [Building Backbone apps with Ruby, Sinatra, Haml and MongoDB](#stack2)
  22. * [Paginating Backbone.js Requests & Collections](#pagination)
  23. * ####[Advanced](#advanced)
  24. * [Modular JavaScript](#modularjs)
  25. * [Organizing modules with RequireJS and AMD](#organizingmodules)
  26. * [Keeping your templates external with the RequireJS text plugin](#externaltemplates)
  27. * [Optimizing Backbone apps for production with the RequireJS Optimizer](#optimizingrequirejs)
  28. * [Practical: Building a modular Backbone app with AMD & RequireJS](#practicalrequirejs)
  29. * [Decoupling Backbone with the Mediator and Facade patterns](#decouplingbackbone)
  30. * Backbone & jQuery Mobile
  31. * Practical: Building A Modular Mobile App With Backbone & jQuery Mobile
  32. * ####[Unit Testing](#testing)
  33. * [Unit Testing Backbone Applications With Jasmine](#unittestingjasmine)
  34. * Introduction
  35. * Jasmine
  36. * Suites, Specs And Spies
  37. * TDD With Backbone
  38. * [Testing Models](#testing-jasmine-models)
  39. * [Testing Collections](#testing-jasmine-collections)
  40. * [Testing Views](#testing-jasmine-views)
  41. * [Unit Testing Backbone Applications With QUnit And SinonJS](#unittestingqunit)
  42. * Introduction
  43. * QUnit
  44. * Assertions
  45. * Adding structure to assertions
  46. * Assertion examples
  47. * Fixtures
  48. * Asynchronous code
  49. * SinonJS
  50. * Stubs
  51. * Mocks
  52. * Practical
  53. * Testing Models
  54. * Testing Collections
  55. * Testing Views
  56. * Testing Events
  57. * ####[Resources](#resources)
  58. <a name="introduction">Introduction</a>
  59. ---
  60. As JavaScript developers, we are at an interesting point in time where not only do we have mature solutions to help organize the JavaScript powering our applications based on a separation of concerns, but developers looking to build non-trivial projects are almost spoiled for choice for frameworks that can help structure their applications.
  61. Maturity in software (framework) development isn't simply about how long a framework has been around. It's about how solid the framework is and more importantly how well it's evolved to fill its role. Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it?
  62. In this book, I will be covering the popular Backbone.js, which I consider the best of the current family of JavaScript architectural frameworks.
  63. Topics will include MVC theory and how to build applications using Backbone's models, views, collections and routers. I'll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), how to build applications using modern software stacks (like Node and Express), how to solve the routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and a lot more.
  64. If this is your first time looking at Backbone.js and you're still unsure whether or not to give it a try, why not take a look at how [a Todo application](http://github.com/addyosmani/todomvc) can be implemented in Backbone and several other popular Javascript frameworks before reading further?
  65. The goal of this book is to create an authoritative and centralized repository of information that can help those developing real-world apps with Backbone. If you come across a section or topic which you think could be improved or expanded on, please feel free to submit a pull-request. It won't take long and you'll be helping other developers avoid problems you've run into before.
  66. ## <a name="fundamentals">Fundamentals</a>
  67. In this section we are going to cover the context into which a framework like Backbone.js fits. Let's begin our journey into understanding Backbone better with a look at code architecture.
  68. ###<a name="mvc-mvp">MVC, MVP & Backbone.js</a>
  69. Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns. Design patterns are proven solutions to common development problems and can suggest structural approaches to help guide developers in adding some organization to their applications.
  70. Patterns are useful because they're a set of practices that build upon the collective experience of skilled developers who have repeatedly solved similar problems. Although developers 10 or 20 years ago may not have been using the same programming languages when implementing patterns in their projects, there are many lessons we can learn from their efforts.
  71. In this section, we're going to review two popular patterns - MVC and MVP. We'll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in.
  72. ##MVC
  73. MVC (Model-View-Controller) is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally present to manage logic, user-input and the coordination of models and views. The pattern was originally designed by [Trygve Reenskaug](http://en.wikipedia.org/wiki/Trygve_Reenskaug) while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in [“Design Patterns: Elements of Reusable Object-Oriented Software”](http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612) (The "GoF" or “Gang of Four” book) in 1994, which played a role in popularizing its use.
  74. ###Smalltalk-80 MVC
  75. It's important to understand what the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70's, graphical user-interfaces were far and few between. An approach known as [Separated Presentation](http://martinfowler.com/eaaDev/uiArchs.html) began to be used as a means to make a clear division between domain objects which modeled concepts in the real world (e.g a photo, a person) and the presentation objects which were rendered to the user's screen.
  76. The Smalltalk-80 implementation of MVC took this concept further and had an objective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of models for other interfaces in the application. There are some interesting points worth noting about Smalltalk-80's MVC architecture:
  77. * A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers)
  78. * Presentation was taken care of by the View and the Controller, but there wasn't just a single view and controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them
  79. * The Controller's role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.
  80. * The Observer pattern was relied upon for updating the View whenever the Model changed
  81. Developers are sometimes surprised when they learn that the Observer pattern (nowadays commonly implemented as a Publish/Subscribe system) was included as a part of MVC's architecture decades ago. In Smalltalk-80's MVC, the View and Controller both observe the Model: anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - for the application to show real-time information, any change to the data in its Models should result in the View being refreshed instantly.
  82. Martin Fowler has done an excellent job of writing about the [origins](http://martinfowler.com/eaaDev/uiArchs.html) of MVC over the years and if you are interested in further historical information about Smalltalk-80's MVC, I recommend reading his work.
  83. ##MVC As We Know It
  84. We've reviewed the 70's, but let us now return to the here and now. The MVC pattern has been applied to a diverse range of programming languages. For example, the popular Ruby on Rails is an implementation of a web application framework based on MVC for the Ruby language. JavaScript now has a number of MVC frameworks, including Ember.js, JavaScriptMVC, and of course Backbone.js. Given the importance of avoiding "spaghetti" code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let's look at what the MVC pattern enables the Javascript developer to do.
  85. MVC is composed of three core components:
  86. ###Models
  87. Models manage the data for an application. They are concerned with neither the user-interface nor presentation layers, but instead represent structured data that an application may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has occurred so that they may react accordingly.
  88. To understand models better, let us imagine we have a JavaScript photo gallery application. In a photo gallery, a photo would merit its own model, as it represents a unique kind of domain-specific data. The Photo model may represent attributes such as a caption, image source and additional meta-data. A specific photo would be stored in an instance of a model. Here's an example of a simple Photo model implemented with Backbone.js:
  89. ```javascript
  90. var Photo = Backbone.Model.extend({
  91. // Default attributes for the photo
  92. defaults: {
  93. // Ensure that each photo created has an `src`.
  94. src: "placeholder.jpg",
  95. caption: "A default image",
  96. viewed: false
  97. },
  98. initialize: function() {
  99. }
  100. });
  101. ```
  102. The built-in capabilities of models vary across frameworks, however it's common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also need a way of persisting models. Persistence allows us to edit and update models with the knowledge that their most recent states will be saved somewhere, for example in a web browser's localStorage data-store or synchronized with a database.
  103. A model may also have multiple views observing it. Imagine our Photo model contained meta-data such as the longitude and latitude where the photo was taken, a list of people present in the photo, and a list of tags. A developer could create a single view that displayed all these attributes, or might create three separate views to display each attribute. The important detail is that the Photo model doesn't care how these views are organized, it simply announces updates to its data as necessary. We'll come back to Views in more detail later.
  104. It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called "Collections". Managing models in groups allows us to write application logic based on notifications from the group, should any model it contains change. This avoids the need to manually observe individual model instances.
  105. Here's how we might group Photo models into a simplified Backbone Collection:
  106. ```javascript
  107. var PhotoGallery = Backbone.Collection.extend({
  108. // Reference to this collection's model.
  109. model: Photo,
  110. // Filter down the list of all photos that have been viewed
  111. viewed: function() {
  112. return this.filter(function(photo){ return photo.get('viewed'); });
  113. },
  114. // Filter down the list to only photos that have not yet been viewed
  115. unviewed: function() {
  116. return this.without.apply(this, this.viewed());
  117. }
  118. });
  119. ```
  120. If you read older texts on MVC, you may come across a description of models as also managing application 'state'. In JavaScript applications "state" has a specific meaning, typically referring to the current "state" of a view or sub-view on a user's screen at a fixed time. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated.
  121. ###Views
  122. Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, allowing the view to update itself accordingly. Design pattern literature commonly refers to views as 'dumb', given that their knowledge of models and controllers in an application is limited.
  123. Users interact with views, which usually means reading and editing model data. For example, in our photo gallery application example, model viewing might happen in a user interface with a big image, a caption, and a list of tags. Model editing could be done through an "edit" view where a user who has selected a specific photo could edit its caption, tags, or other metadata in a form.
  124. In MVC, the actual task of updating the Model falls to Controllers, which we'll be covering shortly.
  125. Let's explore Views a little further using a simple JavaScript example. Below we can see a function that creates a single Photo view, consuming both a model instance and a controller instance.
  126. We define a ```render()``` utility within our view which is responsible for rendering the contents of the ```photoModel``` using a JavaScript templating engine (Underscore templating) and updating the contents of our view, referenced by ```photoEl```.
  127. The ```photoModel``` then adds our ```render()``` callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes.
  128. You may wonder where user interaction comes into play here. When users click on any elements within the view, it's not the view's responsibility to know what to do next. A Controller makes this decision. In our sample implementation, this is achieved by adding an event listener to ```photoEl``` which will delegate handling the click behavior back to the controller, passing the model information along with it in case it's needed.
  129. The benefit of this architecture is that each component plays its own separate role in making the application function as needed.
  130. ```javascript
  131. var buildPhotoView = function( photoModel, photoController ){
  132. var base = document.createElement('div'),
  133. photoEl = document.createElement('div');
  134. base.appendChild(photoEl);
  135. var render= function(){
  136. // We use a templating library such as Underscore
  137. // templating which generates the HTML for our
  138. // photo entry
  139. photoEl.innerHTML = _.template('photoTemplate', {src: photoModel.getSrc()});
  140. }
  141. photoModel.addSubscriber( render );
  142. photoEl.addEventListener('click', function(){
  143. photoController.handleEvent('click', photoModel );
  144. });
  145. var show = function(){
  146. photoEl.style.display = '';
  147. }
  148. var hide = function(){
  149. photoEl.style.display = 'none';
  150. }
  151. return{
  152. showView: show,
  153. hideView: hide
  154. }
  155. }
  156. ```
  157. **Templating**
  158. In the context of JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views.
  159. It has long been considered bad practice (and computationally expensive) to manually create large blocks of HTML markup in-memory through string concatenation. Developers using this technique often find themselves iterating through their data, wrapping it in nested divs and using outdated techniques such as ```document.write``` to inject the 'template' into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.
  160. JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to define templates for views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g 'text/template'). Variables are delimited using a variable syntax (e.g {{name}}). Javascript template libraries typically accept data in JSON, and the grunt work of populating templates with data is taken care of by the framework itself. This has a several benefits, particularly when opting to store templates externally as this can let applications load templates dynamically on an as-needed basis.
  161. Let's compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore's 'microtemplates'.
  162. **Handlebars.js:**
  163. ```html
  164. <li class="photo">
  165. <h2>{{caption}}</h2>
  166. <img class="source" src="{{src}}"/>
  167. <div class="meta-data">
  168. {{metadata}}
  169. </div>
  170. </li>
  171. ```
  172. **Underscore.js Microtemplates:**
  173. ```html
  174. <li class="photo">
  175. <h2><%= caption %></h2>
  176. <img class="source" src="<%= src %>"/>
  177. <div class="meta-data">
  178. <%= metadata %>
  179. </div>
  180. </li>
  181. ```
  182. You may also use double curly brackets (i.e ```{{}}```) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore ```templateSettings``` attribute as follows:
  183. ```javascript
  184. _.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
  185. ```
  186. **A note on navigation and state**
  187. It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn't automatically update the URL, the role of navigation thus falls to a "router", which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.
  188. ###Controllers
  189. Controllers are an intermediary between models and views which are classically responsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view.
  190. In our photo gallery application, a controller would be responsible for handling changes the user made to the edit view for a particular photo, updating a specific photo model when a user has finished editing.
  191. It's with controllers that most JavaScript MVC frameworks depart from this interpretation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript framework authors likely initially looked at server-side interpretations of MVC (such as Ruby on Rails), realized that that approach didn't translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the "proper" role of controllers in other non-Javascript frameworks.
  192. So does Backbone.js have Controllers? Not really. Backbone's Views typically contain "controller" logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC.
  193. In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It's in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects.
  194. ### Controllers in Spine.js vs Backbone.js
  195. **Spine.js**
  196. We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). Since Backbone doesn't have its **own** explicit controllers, it's useful to review the controller from another MVC framework to appreciate the difference in implementations. Let's take a look at [Spine.js](http://spinejs.com/):
  197. In this example, we're going to have a controller called ```PhotosController``` which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user edited the photo meta-data) the corresponding model does too.
  198. (Note: We won't be delving heavily into Spine.js beyond this example, but it's worth looking at it to learn more about Javascript frameworks in general.)
  199. ```javascript
  200. // Controllers in Spine are created by inheriting from Spine.Controller
  201. var PhotosController = Spine.Controller.sub({
  202. init: function(){
  203. this.item.bind("update", this.proxy(this.render));
  204. this.item.bind("destroy", this.proxy(this.remove));
  205. },
  206. render: function(){
  207. // Handle templating
  208. this.replace($("#photoTemplate").tmpl(this.item));
  209. return this;
  210. },
  211. remove: function(){
  212. this.$el.remove();
  213. this.release();
  214. }
  215. });
  216. ```
  217. In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller).
  218. What we're doing in the above example is setting up listeners in the ```update``` and ```destroy``` events using ```render()``` and ```remove()```. When a photo entry gets updated, we re-render the view to reflect the changes to the meta-data. Similarly, if the photo gets deleted from the gallery, we remove it from the view. In case you were wondering about the ```tmpl()``` function in the code snippet: in the ```render()``` function, we're using this to render a JavaScript template called #photoTemplate which simply returns a HTML string used to replace the controller's current element.
  219. What this provides us with is a very lightweight, simple way to manage changes between the model and the view.
  220. **Backbone.js**
  221. Later on in this section we're going to revisit the differences between Backbone and traditional MVC, but for now let's focus on controllers.
  222. In Backbone, controller logic is shared between Backbone.View and Backbone.Router. Earlier releases of Backbone contained something called Backbone.Controller, but it was renamed to Router to clarify its role.
  223. A Router's main purpose is to translate URL requests into application states. When a user browses to the URL www.example.com/photos/42, a Router could be used to show the photo with that ID, and to define what application behavior should be run in response to that request. Routers *can* contain traditional controller responsibilities, such as binding the events between models and views, or rendering parts of the page. However, Backbone contributor Tim Branyen has pointed out that it's possible to get away without needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably:
  224. ```javascript
  225. var PhotoRouter = Backbone.Router.extend({
  226. routes: { "photos/:id": "route" },
  227. route: function(id) {
  228. var item = photoCollection.get(id);
  229. var view = new PhotoView({ model: item });
  230. something.html( view.render().el );
  231. }
  232. }):
  233. ```
  234. ##What does MVC give us?
  235. To summarize, the separation of concerns in MVC facilitates modularization of an application's functionality and enables:
  236. * Easier overall maintenance. When updates need to be made to the application it is clear whether the changes are data-centric, meaning changes to models and possibly controllers, or merely visual, meaning changes to views.
  237. * Decoupling models and views means that it's straight-forward to write unit tests for business logic
  238. * Duplication of low-level model and controller code is eliminated across the application
  239. * Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user-interfaces to work simultaneously
  240. ###Delving deeper
  241. Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we'll explore it a little further.
  242. The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a "set of classes to build a user interface". In their view, it's actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I've covered some of these patterns in my other free book, JavaScript Design Patterns For Beginners if you would like to read into them further.
  243. As we've discussed, models represent application data, while views handle what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core communication (something that surprisingly isn't covered in many articles about the MVC pattern). When a model is changed it "publishes" to the rest of the application that it has been updated. The "subscriber"--generally a Controller--then updates the view accordingly. The observer-viewer nature of this relationship is what facilitates multiple views being attached to the same model.
  244. For developers interested in knowing more about the decoupled nature of MVC (once again, depending on the implementation), one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different relationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern.
  245. ###Summary
  246. Having reviewed the classical MVC pattern, your should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.
  247. When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it's opted to approach Models, Views, Controllers or other alternatives, as this can better help you grok how the framework expects to be used.
  248. ##MVP
  249. Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named [Taligent](http://en.wikipedia.org/wiki/Taligent) in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple components, there are some fundamental differences between them.
  250. For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.
  251. ###Models, Views & Presenters
  252. The P in MVP stands for presenter. It's a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests.
  253. The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes "dumb"), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other. They effectively bind models to views, a responsibility held by Controllers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views.
  254. Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it's the presenter's role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data.
  255. The benefit of this change from MVC is that it increases the testability of your application and provides a more clean separation between the view and the model. This isn't however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately.
  256. Although a common implementation of a [Passive View](http://martinfowler.com/eaaDev/PassiveScreen.html) is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don't have the interface construct in JavaScript, we're using it more as more a protocol than an explicit interface here. It's technically still an API and it's probably fair for us to refer to it as an interface from that perspective.
  257. There is also a [Supervising Controller](http://martinfowler.com/eaaDev/SupervisingPresenter.html) variation of MVP, which is closer to the MVC and [MVVM](http://en.wikipedia.org/wiki/Model_View_ViewModel) patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey's Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone.
  258. ##MVP or MVC?
  259. MVP is generally used most often in enterprise-level applications where it's necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn't quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly.
  260. As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application.
  261. Depending on the implementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other components. In my experience this really depends on the languages you are implementing MVP in (there's quite a difference between opting for MVP for a JavaScript project over one for say, ASP.net).
  262. At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for.
  263. ##MVC, MVP and Backbone.js
  264. There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVP patterns in their classical form as many JavaScript developers don't view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.net or GWT). This is because it's possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC.
  265. Backbone contributor [Irene Ros](http://ireneros.com/) subscribes to this way of thinking as when she separates Backbone views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a ```Backbone.Router```, covered later in the book) or a callback in response to data being fetched.
  266. That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC
  267. . Their view is that:
  268. * The presenter in MVP better describes the ```Backbone.View``` (the layer between View templates and the data bound to it) than a controller does
  269. * The model fits ```Backbone.Model``` (it isn't that different from the classical MVC "Model")
  270. * The views best represent templates (e.g Handlebars/Mustache markup templates)
  271. A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by ```Backbone.View``` because they're able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.
  272. We've also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true.
  273. Here, our Backbone ```PhotoView``` uses the Observer pattern to 'subscribe' to changes to a View's model in the line ```this.model.on('change',...)```. It also handles templating in the ```render()``` method, but unlike some other implementations, user interaction is also handled in the View (see ```events```).
  274. ```javascript
  275. var PhotoView = Backbone.View.extend({
  276. //... is a list tag.
  277. tagName: "li",
  278. // Pass the contents of the photo template through a templating
  279. // function, cache it for a single photo
  280. template: _.template($('#photo-template').html()),
  281. // The DOM events specific to an item.
  282. events: {
  283. "click img" : "toggleViewed"
  284. },
  285. // The PhotoView listens for changes to its model, re-rendering. Since there's
  286. // a one-to-one correspondence between a **Photo** and a **PhotoView** in this
  287. // app, we set a direct reference on the model for convenience.
  288. initialize: function() {
  289. _.bindAll(this, 'render');
  290. this.model.on('change', this.render);
  291. this.model.on('destroy', this.remove);
  292. },
  293. // Re-render the photo entry
  294. render: function() {
  295. this.$el.html(this.template(this.model.toJSON()));
  296. return this;
  297. },
  298. // Toggle the `"viewed"` state of the model.
  299. toggleViewed: function() {
  300. this.model.viewed();
  301. }
  302. });
  303. ```
  304. Another (quite different) opinion is that Backbone more closely resembles [Smalltalk-80 MVC](http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController), which we went through earlier.
  305. As regular Backbone user Derick Bailey has [written](http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/), it's ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone doesn't fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well. Call it **the Backbone way**, MV* or whatever helps reference its flavor of application architecture.
  306. It *is* however worth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained.
  307. ##Fast facts
  308. ###Backbone.js
  309. * Core components: Model, View, Collection, Router. Enforces its own flavor of MV*
  310. * Good documentation, with more improvements on the way
  311. * Used by large companies such as SoundCloud and Foursquare to build non-trivial applications
  312. * Event-driven communication between views and models. As we'll see, it's relatively straight-forward to add event listeners to any attribute in a model, giving developers fine-grained control over what changes in the view
  313. * Supports data bindings through manual events or a separate Key-value observing (KVO) library
  314. * Great support for RESTful interfaces out of the box, so models can be easily tied to a backend
  315. * Extensive eventing system. It's [trivial](http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/) to add support for pub/sub in Backbone
  316. * Prototypes are instantiated with the ```new``` keyword, which some developers prefer
  317. * Agnostic about templating frameworks, however Underscore's micro-templating is available by default. Backbone works well with libraries like Handlebars
  318. * Doesn't support deeply nested models, though there are Backbone plugins such as [this](https://github.com/PaulUithol/Backbone-relational) which can help
  319. * Clear and flexible conventions for structuring applications. Backbone doesn't force usage of all of its components and can work with only those needed.
  320. ## <a name="thebasics">The Basics</a>
  321. ---
  322. ###What is Backbone?
  323. Backbone.js is one of a number of JavaScript frameworks for creating MVC-like web applications. On the front-end, it's my architectural framework of choice as it's both mature, relatively lightweight and can be easily tested using third-party toolkits such as Jasmine or QUnit. Other MVC frameworks you may be familiar with include Ember.js (SproutCore 2.0), Spine, YUILibrary and JavaScriptMVC.
  324. Backbone is maintained by a number of contributors, most notably: Jeremy Ashkenas, creator of CoffeeScript, Docco and Underscore.js. As Jeremy is a believer in detailed documentation, there's a level of comfort in knowing you're unlikely to run into issues which are either not explained in the official docs or which can't be nailed down with some assistance from the #documentcloud IRC channel. I strongly recommend using the latter if you find yourself getting stuck.
  325. ###Why should you consider using it?
  326. Backbone's main benefits, regardless of your target platform or device, include helping:
  327. * Organize the structure to your application
  328. * Simplify server-side persistence
  329. * Decouple the DOM from your page's data
  330. * Model data, views and routers in a succinct manner
  331. * Provide DOM, model and collection synchronization
  332. ##The Basics
  333. In this section, you'll learn the essentials of Backbone's models, views, collections and routers, as well as about using namespacing to organize your code. This isn't meant as a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications with it.
  334. * Models
  335. * Collections
  336. * Routers
  337. * Views
  338. * Namespacing
  339. ###<a name="models">Models</a>
  340. Backbone models contain interactive data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a photo object including its attributes like tags, titles and a location.
  341. Models can be created by extending `Backbone.Model` as follows:
  342. ```javascript
  343. var Photo = Backbone.Model.extend({
  344. defaults: {
  345. src: 'placeholder.jpg',
  346. title: 'an image placeholder',
  347. coordinates: [0,0]
  348. },
  349. initialize: function(){
  350. this.on("change:src", function(){
  351. var src = this.get("src");
  352. console.log('Image source updated to ' + src);
  353. });
  354. },
  355. changeSrc: function( source ){
  356. this.set({ src: source });
  357. }
  358. });
  359. var somePhoto = new Photo({ src: "test.jpg", title:"testing"});
  360. somePhoto.changeSrc("magic.jpg"); // which triggers "change:src" and logs an update message to the console.
  361. ```
  362. ####Initialization
  363. The `initialize()` method is called when a new instance of a model is created. Its use is optional, however you'll see why it's good practice to use it below.
  364. ```javascript
  365. var Photo = Backbone.Model.extend({
  366. initialize: function(){
  367. console.log('this model has been initialized');
  368. }
  369. });
  370. // We can then create our own instance of a photo as follows:
  371. var myPhoto = new Photo();
  372. ```
  373. ####Getters & Setters
  374. **Model.get()**
  375. `Model.get()` provides easy access to a model's attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval.
  376. ```javascript
  377. var myPhoto = new Photo({ title: "My awesome photo",
  378. src:"boston.jpg",
  379. location: "Boston",
  380. tags:['the big game', 'vacation']}),
  381. title = myPhoto.get("title"), //My awesome photo
  382. location = myPhoto.get("location"), //Boston
  383. tags = myPhoto.get("tags"), // ['the big game','vacation']
  384. photoSrc = myPhoto.get("src"); //boston.jpg
  385. ```
  386. Alternatively, if you wish to directly access all of the attributes in a model's instance directly, you can achieve this as follows:
  387. ```javascript
  388. var myAttributes = myPhoto.attributes;
  389. console.log(myAttributes);
  390. ```
  391. It is best practice to use `Model.set()` or direct instantiation to set the values of a model's attributes.
  392. Accessing `Model.attributes` directly is generally discouraged. Instead, should you need to read or clone data, `Model.toJSON()` is recommended for this purpose. If you would like to access or copy a model's attributes for purposes such as JSON stringification (e.g. for serialization prior to being passed to a view), this can be achieved using `Model.toJSON()`:
  393. ```javascript
  394. var myAttributes = myPhoto.toJSON();
  395. console.log(myAttributes);
  396. /* this returns { title: "My awesome photo",
  397. src:"boston.jpg",
  398. location: "Boston",
  399. tags:['the big game', 'vacation']}*/
  400. ```
  401. ####Model.set()
  402. `Model.set()` allows us to pass attributes into an instance of our model. Attributes can either be set during initialization or at any time afterwards. It's important to avoid trying to set a Model's attributes directly (for example Model.caption = 'A new caption'). Backbone uses Model.set() to know when to broadcast that a model's data has changed.
  403. ```javascript
  404. var Photo = Backbone.Model.extend({
  405. initialize: function(){
  406. console.log('this model has been initialized');
  407. }
  408. });
  409. // Setting the value of attributes via instantiation
  410. var myPhoto = new Photo({ title: 'My awesome photo', location: 'Boston' });
  411. var myPhoto2 = new Photo();
  412. // Setting the value of attributes through Model.set()
  413. myPhoto2.set({ title:'Vacation in Florida', location: 'Florida' });
  414. ```
  415. **Default values**
  416. There are times when you want your model to have a set of default values (e.g. in a scenario where a complete set of data isn't provided by the user). This can be set using a property called `defaults` in your model.
  417. ```javascript
  418. var Photo = Backbone.Model.extend({
  419. defaults:{
  420. title: 'Another photo!',
  421. tags: ['untagged'],
  422. location: 'home',
  423. src: 'placeholder.jpg'
  424. },
  425. initialize: function(){
  426. }
  427. });
  428. var myPhoto = new Photo({ location: "Boston",
  429. tags:['the big game', 'vacation']}),
  430. title = myPhoto.get("title"), //Another photo!
  431. location = myPhoto.get("location"), //Boston
  432. tags = myPhoto.get("tags"), // ['the big game','vacation']
  433. photoSrc = myPhoto.get("src"); //placeholder.jpg
  434. ```
  435. **Listening for changes to your model**
  436. Any and all of the attributes in a Backbone model can have listeners bound to them which detect when their values change. Listeners can be added to the `initialize()` function:
  437. ```javascript
  438. this.on('change', function(){
  439. console.log('values for this model have changed');
  440. });
  441. ```
  442. In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered.
  443. ```javascript
  444. var Photo = Backbone.Model.extend({
  445. defaults:{
  446. title: 'Another photo!',
  447. tags: ['untagged'],
  448. location: 'home',
  449. src: 'placeholder.jpg'
  450. },
  451. initialize: function(){
  452. console.log('this model has been initialized');
  453. this.on("change:title", function(){
  454. var title = this.get("title");
  455. console.log("My title has been changed to.. " + title);
  456. });
  457. },
  458. setTitle: function(newTitle){
  459. this.set({ title: newTitle });
  460. }
  461. });
  462. var myPhoto = new Photo({ title:"Fishing at the lake", src:"fishing.jpg"});
  463. myPhoto.setTitle('Fishing at sea');
  464. //logs 'My title has been changed to.. Fishing at sea'
  465. ```
  466. **Validation**
  467. Backbone supports model validation through `Model.validate()`, which allows checking the attribute values for a model prior to them being set.
  468. Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from `.validate()`. If they are invalid, a custom error can be returned instead.
  469. A basic example for validation can be seen below:
  470. ```javascript
  471. var Photo = Backbone.Model.extend({
  472. validate: function(attribs){
  473. if(attribs.src === undefined){
  474. return "Remember to set a source for your image!";
  475. }
  476. },
  477. initialize: function(){
  478. console.log('this model has been initialized');
  479. this.on("error", function(model, error){
  480. console.log(error);
  481. });
  482. }
  483. });
  484. var myPhoto = new Photo();
  485. myPhoto.set({ title: "On the beach" });
  486. //logs Remember to set a source for your image!
  487. ```
  488. ###<a name="views">Views</a>
  489. Views in Backbone don't contain the markup for your application, but rather they are there to support models by defining the logic for how they should be represented to the user. This is usually achieved using JavaScript templating (e.g. Mustache, jQuery-tmpl, etc.). A view's `render()` function can be bound to a model's `change()` event, allowing the view to always be up to date without requiring a full page refresh.
  490. ####Creating new views
  491. Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend `Backbone.View`. I'll explain this code in detail below:
  492. ```javascript
  493. var PhotoSearch = Backbone.View.extend({
  494. el: $('#results'),
  495. render: function( event ){
  496. var compiled_template = _.template( $("#results-template").html() );
  497. this.$el.html( compiled_template(this.model.toJSON()) );
  498. return this; //recommended as this enables calls to be chained.
  499. },
  500. events: {
  501. "submit #searchForm": "search",
  502. "click .reset": "reset",
  503. "click .advanced": "switchContext"
  504. },
  505. search: function( event ){
  506. //executed when a form '#searchForm' has been submitted
  507. },
  508. reset: function( event ){
  509. //executed when an element with class "reset" has been clicked.
  510. },
  511. switchContext: function( event ){
  512. //executed when an element with class "advanced" has been clicked.
  513. }
  514. });
  515. ```
  516. ####What is `el`?
  517. `el` is basically a reference to a DOM element and all views must have one. It allows for all of the contents of a view to be inserted into the DOM at once, which makes for faster rendering as browser performs the minimum required reflows and repaints.
  518. There are two ways to attach a DOM element to a view: the element already exists in the page or a new element is created for the view and added manually by the developer.
  519. If the element already exists in the page, you can set `el` as either a CSS selector that matches the element or a simple reference to the DOM element.
  520. ```javascript
  521. el: '#footer',
  522. // OR
  523. el: document.getElementById( 'footer' )
  524. ```
  525. If you want to create a new element for your view, set any combination of the following view's properties: `tagName`, `id` and `className`. A new element will be created for you by the framework and a reference to it will be available at the `el` property.
  526. ```
  527. tagName: 'p', // required, but defaults to 'div' if not set
  528. className: 'container', // optional, you can assign multiple classes to this property like so 'container homepage'
  529. id: 'header', // optional
  530. ```
  531. The above code creates the ```DOMElement``` below but does

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