PageRenderTime 102ms CodeModel.GetById 23ms 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
  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 doesn't append it to the DOM.
  532. <p id="header" class="container"></p>
  533. **Understanding `render()`**
  534. `render()` is an optional function that defines the logic for rendering a template. We'll use Underscore's micro-templating in these examples, but remember you can use other templating frameworks if you prefer.
  535. The `_.template` method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the above view, I'm passing the markup from a template with id `results-template` to `_.template()` to be compiled. Next, I set the html of the `el` DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.
  536. Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.
  537. **The `events` attribute**
  538. The Backbone `events` attribute allows us to attach event listeners to either custom selectors, or directly to `el` if no selector is provided. An event takes the form `{"eventName selector": "callbackFunction"}` and a number of event-types are supported, including `click`, `submit`, `mouseover`, `dblclick` and more.
  539. What isn't instantly obvious is that under the bonnet, Backbone uses jQuery's `.delegate()` to provide instant support for event delegation but goes a little further, extending it so that `this` always refers to the current view object. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.
  540. ###<a name="collections">Collections</a>
  541. Collections are sets of Models and are created by extending `Backbone.Collection`.
  542. Normally, when creating a collection you'll also want to pass through a property specifying the model that your collection will contain, as well as any instance properties required.
  543. In the following example, we create a PhotoCollection that will contain our Photo models:
  544. ```javascript
  545. var PhotoCollection = Backbone.Collection.extend({
  546. model: Photo
  547. });
  548. ```
  549. **Getters and Setters**
  550. There are a few different ways to retrieve a model from a collection. The most straight-forward is to use `Collection.get()` which accepts a single id as follows:
  551. ```javascript
  552. var skiingEpicness = PhotoCollection.get(2);
  553. ```
  554. Sometimes you may also want to get a model based on its client id. The client id is a property that Backbone automatically assigns models that have not yet been saved. You can get a model's client id from its `.cid` property.
  555. ```javascript
  556. var mySkiingCrash = PhotoCollection.getByCid(456);
  557. ```
  558. Backbone Collections don't have setters as such, but do support adding new models via `.add()` and removing models via `.remove()`.
  559. ```javascript
  560. var a = new Backbone.Model({ title: 'my vacation'}),
  561. b = new Backbone.Model({ title: 'my holiday'});
  562. var photoCollection = new PhotoCollection([a,b]);
  563. photoCollection.remove([a,b]);
  564. ```
  565. **Listening for events**
  566. As collections represent a group of items, we're also able to listen for `add` and `remove` events for when new models are added or removed from the collection. Here's an example:
  567. ```javascript
  568. var PhotoCollection = new Backbone.Collection();
  569. PhotoCollection.on("add", function(photo) {
  570. console.log("I liked " + photo.get("title") + ' its this one, right? ' + photo.get("src"));
  571. });
  572. PhotoCollection.add([
  573. {title: "My trip to Bali", src: "bali-trip.jpg"},
  574. {title: "The flight home", src: "long-flight-oofta.jpg"},
  575. {title: "Uploading pix", src: "too-many-pics.jpg"}
  576. ]);
  577. ```
  578. In addition, we're able to bind a `change` event to listen for changes to models in the collection.
  579. ```javascript
  580. PhotoCollection.on("change:title", function(){
  581. console.log('there have been updates made to this collections titles');
  582. });
  583. ```
  584. **Fetching models from the server**
  585. `Collections.fetch()` retrieves a default set of models from the server in the form of a JSON array. When this data returns, the current collection's contents will be replaced with the contents of the array.
  586. ```javascript
  587. var PhotoCollection = new Backbone.Collection;
  588. PhotoCollection.url = '/photos';
  589. PhotoCollection.fetch();
  590. ```
  591. Under the covers, `Backbone.sync` is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto's ajax implementations to make these RESTful requests, however this can be overridden as per your needs.
  592. In the above example if we wanted to log an event when `.sync()` was called, we could do this:
  593. ```javascript
  594. Backbone.sync = function(method, model) {
  595. console.log("I've been passed " + method + " with " + JSON.stringify(model));
  596. };
  597. ```
  598. **Resetting/Refreshing Collections**
  599. Rather than adding or removing models individually, you might occasionally wish to update an entire collection at once. `Collection.reset()` allows us to replace an entire collection with new models as follows:
  600. ```javascript
  601. PhotoCollection.reset([
  602. {title: "My trip to Scotland", src: "scotland-trip.jpg"},
  603. {title: "The flight from Scotland", src: "long-flight.jpg"},
  604. {title: "Latest snap of lock-ness", src: "lockness.jpg"}]);
  605. ```
  606. Note that using `Collection.reset()` doesn't fire any `add` or `remove` events. A `reset` event is fired instead.
  607. ###Underscore utility functions
  608. As Backbone requires Underscore as a hard dependency, we're able to use many of the utilities it has to offer to aid with our application development. Here's an example of how Underscore's `sortBy()` method can be used to sort a collection of photos based on a particular attribute.
  609. ```javascript
  610. var sortedByAlphabet = PhotoCollection.sortBy(function (photo) {
  611. return photo.get("title").toLowerCase();
  612. });
  613. ```
  614. The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official [docs](http://documentcloud.github.com/underscore/).
  615. ###<a name="routers">Routers</a>
  616. In Backbone, routers are used to help manage application state and for connecting URLs to application events. This is achieved using hash-tags with URL fragments, or using the browser's pushState and History API. Some examples of routes may be seen below:
  617. ```javascript
  618. http://unicorns.com/#whatsup
  619. http://unicorns.com/#search/seasonal-horns/page2
  620. ```
  621. Note: An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that particular route. This relationship is defined as follows:
  622. ```javascript
  623. "route" : "mappedFunction"
  624. ```
  625. Let us now define our first controller by extending `Backbone.Router`. For the purposes of this guide, we're going to continue pretending we're creating a photo gallery application that requires a GalleryRouter.
  626. Note the inline comments in the code example below as they continue the rest of the lesson on routers.
  627. ```javascript
  628. var GalleryRouter = Backbone.Router.extend({
  629. /* define the route and function maps for this router */
  630. routes: {
  631. "about" : "showAbout",
  632. /*Sample usage: http://unicorns.com/#about*/
  633. "photos/:id" : "getPhoto",
  634. /*This is an example of using a ":param" variable which allows us to match
  635. any of the components between two URL slashes*/
  636. /*Sample usage: http://unicorns.com/#photos/5*/
  637. "search/:query" : "searchPhotos",
  638. /*We can also define multiple routes that are bound to the same map function,
  639. in this case searchPhotos(). Note below how we're optionally passing in a
  640. reference to a page number if one is supplied*/
  641. /*Sample usage: http://unicorns.com/#search/lolcats*/
  642. "search/:query/p:page" : "searchPhotos",
  643. /*As we can see, URLs may contain as many ":param"s as we wish*/
  644. /*Sample usage: http://unicorns.com/#search/lolcats/p1*/
  645. "photos/:id/download/*imagePath" : "downloadPhoto",
  646. /*This is an example of using a *splat. splats are able to match any number of
  647. URL components and can be combined with ":param"s*/
  648. /*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/
  649. /*If you wish to use splats for anything beyond default routing, it's probably a good
  650. idea to leave them at the end of a URL otherwise you may need to apply regular
  651. expression parsing on your fragment*/
  652. "*other" : "defaultRoute"
  653. /*This is a default route that also uses a *splat. Consider the
  654. default route a wildcard for URLs that are either not matched or where
  655. the user has incorrectly typed in a route path manually*/
  656. /*Sample usage: http://unicorns.com/#anything*/
  657. },
  658. showAbout: function(){
  659. },
  660. getPhoto: function(id){
  661. /*
  662. Note that the id matched in the above route will be passed to this function
  663. */
  664. console.log("You are trying to reach photo " + id);
  665. },
  666. searchPhotos: function(query, page){
  667. var page_number = page || 1;
  668. console.log("Page number: " + page_number + " of the results for " + query);
  669. },
  670. downloadPhoto: function(id, path){
  671. },
  672. defaultRoute: function(other){
  673. console.log("Invalid. You attempted to reach:" + other);
  674. }
  675. });
  676. /* Now that we have a router setup, remember to instantiate it*/
  677. var myGalleryRouter = new GalleryRouter();
  678. ```
  679. As of Backbone 0.5+, it's possible to opt-in for HTML5 pushState support via `window.history.pushState`. This permits you to define routes such as http://www.scriptjunkie.com/just/an/example. This will be supported with automatic degradation when a user's browser doesn't support pushState. For the purposes of this tutorial, we'll use the hashtag method.
  680. ####Backbone.history
  681. Next, we need to initialize `Backbone.history` as it handles `hashchange` events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.
  682. The `Backbone.history.start()` method will simply tell Backbone that it's OK to begin monitoring all `hashchange` events as follows:
  683. ```javascript
  684. Backbone.history.start();
  685. Router.navigate();
  686. ```
  687. As an aside, if you would like to save application state to the URL at a particular point you can use the `.navigate()` method to achieve this. It simply updates your URL fragment without the need to trigger the `hashchange` event:
  688. ```javascript
  689. /*Lets imagine we would like a specific fragment for when a user zooms into a photo*/
  690. zoomPhoto: function(factor){
  691. this.zoom(factor); //imagine this zooms into the image
  692. this.navigate("zoom/" + factor); //updates the fragment for us, but doesn't trigger the route
  693. }
  694. ```
  695. It is also possible for `Router.navigate()` to trigger the route as well as updating the URL fragment.
  696. ```javascript
  697. zoomPhoto: function(factor){
  698. this.zoom(factor); //imagine this zooms into the image
  699. this.navigate("zoom/" + factor, true); //updates the fragment for us and triggers the route
  700. }
  701. ```
  702. ###<a name="namespacing">Namespacing</a>
  703. When learning how to use Backbone, an important and commonly overlooked area by tutorials is namespacing. If you already have experience with namespacing in JavaScript, the following section will provide some advice on how to specifically apply concepts you know to Backbone, however I will also be covering explanations for beginners to ensure everyone is on the same page.
  704. ####What is namespacing?
  705. The basic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They're important as it's best to safeguard your code from breaking in the event of another script on the page using the same variable names as you are. As a good 'citizen' of the global namespace, it's also imperative that you do your best to similarly not prevent other developer's scripts executing due to the same issues.
  706. JavaScript doesn't really have built-in support for namespaces like other languages, however it does have closures which can be used to achieve a similar effect.
  707. In this section we'll be taking a look shortly at some examples of how you can namespace your models, views, routers and other components specifically. The patterns we'll be examining are:
  708. * Single global variables
  709. * Object Literals
  710. * Nested namespacing
  711. **Single global variables**
  712. One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:
  713. ```javascript
  714. var myApplication = (function(){
  715. function(){
  716. // ...
  717. },
  718. return {
  719. // ...
  720. }
  721. })();
  722. ```
  723. You've probably seen this technique before. A Backbone-specific example might look like this:
  724. ```javascript
  725. var myViews = (function(){
  726. return {
  727. PhotoView: Backbone.View.extend({ .. }),
  728. GalleryView: Backbone.View.extend({ .. }),
  729. AboutView: Backbone.View.extend({ .. });
  730. //etc.
  731. };
  732. })();
  733. ```
  734. Here we can return a set of views, but the same technique could return an entire collection of models, views and routers depending on how you decide to structure your application. Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.
  735. One solution to this problem, as mentioned by Peter Michaux, is to use prefix namespacing. It's a simple concept at heart, but the idea is you select a common prefix name (in this example, `myApplication_`) and then define any methods, variables or other objects after the prefix.
  736. ```javascript
  737. var myApplication_photoView = Backbone.View.extend({}),
  738. myApplication_galleryView = Backbone.View.extend({});
  739. ```
  740. This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow.
  741. For more on Peter's views about the single global variable pattern, read his [excellent post on them](http://michaux.ca/articles/javascript-namespacing).
  742. Note: There are several other variations on the single global variable pattern out in the wild, however having reviewed quite a few, I felt the prefixing approach applied best to Backbone.
  743. **Object Literals**
  744. Object Literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They're beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, Object Literals often also take into account tests for the existence of a variable by the same name, which helps reduce the chances of collision.
  745. This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2.
  746. ```javascript
  747. /*Doesn't check for existence of myApplication*/
  748. var myApplication = {};
  749. /*
  750. Does check for existence. If already defined, we use that instance.
  751. Option 1: if(!myApplication) myApplication = {};
  752. Option 2: var myApplication = myApplication || {};
  753. We can then populate our object literal to support models, views and collections (or any data, really):
  754. */
  755. var myApplication = {
  756. models : {},
  757. views : {
  758. pages : {}
  759. },
  760. collections : {}
  761. };
  762. ```
  763. One can also opt for adding properties directly to the namespace (such as your views, in the following example):
  764. ```javascript
  765. var myGalleryViews = myGalleryViews || {};
  766. myGalleryViews.photoView = Backbone.View.extend({});
  767. myGalleryViews.galleryView = Backbone.View.extend({});
  768. ```
  769. The benefit of this pattern is that you're able to easily encapsulate all of your models, views, routers etc. in a way that clearly separates them and provides a solid foundation for extending your code.
  770. This pattern has a number of benefits. It's often a good idea to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter it. Here's an example of a hypothetical object literal that stores application configuration settings:
  771. ```javascript
  772. var myConfig = {
  773. language: 'english',
  774. defaults: {
  775. enableGeolocation: true,
  776. enableSharing: false,
  777. maxPhotos: 20
  778. },
  779. theme: {
  780. skin: 'a',
  781. toolbars: {
  782. index: 'ui-navigation-toolbar',
  783. pages: 'ui-custom-toolbar'
  784. }
  785. }
  786. }
  787. ```
  788. Note that there are really only minor syntactical differences between the Object Literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g. for simpler storage when sending to the back-end), feel free to.
  789. For more on the Object Literal pattern, I recommend reading Rebecca Murphey's [excellent article on the topic](http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code).
  790. **Nested namespacing**
  791. An extension of the Object Literal pattern is nested namespacing. It's another common pattern used that offers a lower risk of collision due to the fact that even if a top-level namespace already exists, it's unlikely the same nested children do. For example, Yahoo's YUI uses the nested object namespacing pattern extensively:
  792. ```javascript
  793. YAHOO.util.Dom.getElementsByClassName('test');
  794. ```
  795. Yahoo's YUI uses the nested object namespacing pattern regularly and even DocumentCloud (the creators of Backbone) use the nested namespacing pattern in their main applications. A sample implementation of nested namespacing with Backbone may look like this:
  796. ```javascript
  797. var galleryApp = galleryApp || {};
  798. // perform similar check for nested children
  799. galleryApp.routers = galleryApp.routers || {};
  800. galleryApp.model = galleryApp.model || {};
  801. galleryApp.model.special = galleryApp.model.special || {};
  802. // routers
  803. galleryApp.routers.Workspace = Backbone.Router.extend({});
  804. galleryApp.routers.PhotoSearch = Backbone.Router.extend({});
  805. // models
  806. galleryApp.model.Photo = Backbone.Model.extend({});
  807. galleryApp.model.Comment = Backbone.Model.extend({});
  808. // special models
  809. galleryApp.model.special.Admin = Backbone.Model.extend({});
  810. ```
  811. This is readable, clearly organized, and is a relatively safe way of namespacing your Backbone application. The only real caveat however is that it requires your browser's JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you're calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the 'nested' approach to be quite negligible.
  812. **Recommendation**
  813. Reviewing the namespace patterns above, the option that I prefer when writing Backbone applications is nested object namespacing with the object literal pattern.
  814. Single global variables may work fine for applications that are relatively trivial. However, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that's both readable and scalable. I feel this pattern achieves both of these objectives and is a good choice for most Backbone development.
  815. ###<a name="additional-tips">Additional Tips</a>
  816. ####Automated Backbone Scaffolding
  817. Scaffolding can assist in expediting how quickly you can begin a new application by creating the basic files required for a project automatically. If you enjoy the idea of automated MVC scaffolding using Backbone, I'm happy to recommend checking out a tool called [Brunch](https://github.com/brunch/brunch).
  818. It works very well with Backbone, Underscore, jQuery and CoffeeScript and is even used by companies such as Red Bull and Jim Beam. You may have to update any third party dependencies (e.g. latest jQuery or Zepto) when using it, but other than that it should be fairly stable to use right out of the box.
  819. Brunch can be installed via the nodejs package manager and is easy to get started with. If you happen to use Vim or Textmate as your editor of choice, you'll be happy to know that there are Brunch bundles available for both.
  820. ####Is there a limit to the number of routers I should be using?
  821. Andrew de Andrade has pointed out that DocumentCloud themselves usually only use a single router in most of their applications. You're very likely to not require more than one or two routers in your own projects as the majority of your application routing can be kept organized in a single controller without it getting unwieldy.
  822. ####Is Backbone too small for my application's needs?
  823. If you find yourself unsure of whether or not your application is too large to use Backbone, I recommend reading [my post](http://addyosmani.com/blog/jqcon-largescalejs-2012/) on building large-scale jQuery & JavaScript applications or reviewing my slides on client-side MVC architecture options. In both, I cover alternative solutions and my thoughts on the suitability of current MVC solutions for scaled application development.
  824. Backbone can be used for building both trivial and complex applications as demonstrated by the many examples Ashkenas has been referencing in the Backbone documentation. As with any MVC framework however, it's important to dedicate time towards planning out what models and views your application really needs. Diving straight into development without doing this can result in either spaghetti code or a large refactor later on and it's best to avoid this where possible.
  825. At the end of the day, the key to building large applications is not to build large applications in the first place. If you however find Backbone doesn't cut it for your requirements I strongly recommend checking out JavaScriptMVC or SproutCore as these both offer a little more than Backbone out of the box. Dojo and Dojo Mobile may also be of interest as these have also been used to build significantly complex apps by other developers.
  826. ## <a name="restfulapps">RESTful Applications</a>
  827. ---
  828. ##<a name="restful">Building RESTful applications with Backbone</a>
  829. In this section of the book, we're going to take a look at developing RESTful applications using Backbone.js and modern technology stacks. When the data for your back-end is exposed through a purely RESTful API, tasks such as retrieving (GET), creating (POST), updating (PUT) and deleting (DELETE) models are made easy through Backbone's Model API. This API is so intuitive in fact that switching from storing records in a local data-store (e.g localStorage) to a database/noSQL data-store is a lot simpler than you may think.
  830. ##<a name="stack1">Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB</a>
  831. The first stack we'll be looking at is:
  832. * [Node.js](nodejs.org)
  833. * [Express](http://expressjs.com/)
  834. * [Mongoose](http://mongoosejs.com/)
  835. * and [MongoDB](http://www.mongodb.org/)
  836. with [Jade](http://jade-lang.com/) used optionally as a view/templating engine.
  837. ###Reviewing the stack
  838. As you may know, node.js is an event-driven platform (built on the [V8](http://code.google.com/apis/v8/design.html) runtime), designed for writing fast, scalable network applications. It's reasonably lightweight, efficient and great for real-time applications that are data-intensive.
  839. Express is a small web-development framework written with node.js, based on [Sinatra](http://www.sinatrarb.com/). It supports a number of useful features such as intuitive views, robust routing and a focus on high performance.
  840. Next on the list are MongoDB and Mongoose. MongoDB is an open-source, document-oriented database store designed with scalability and agility in mind. As a [noSQL](http://en.wikipedia.org/wiki/NoSQL) database, rather than storing data in tables and rows (something we're very used to doing with relational databases), with MongoDB we instead store JSON-like documents using dynamic schemas. One of the goals of Mongo is to try bridging the gap between key-value stores (speed, scalability) and [relational](http://en.wikipedia.org/wiki/Relational_database) databases (rich functionality).
  841. Mongoose is a JavaScript library that simplifies how we interact with Mongo. Like Express, it's designed to work within the node.js environment and tries to solve some of the complexities with asynchronous data storage by offering a more user-friendly API. It also adds chaining features into the mix, allowing for a slightly more expressive way of dealing with our data.
  842. Jade is a template engine influenced by Haml (which we'll be looking at later). It's implemented with JavaScript (and also runs under node). In addition to supporting Express out of the box, it boasts a number of useful features including support for mixins, includes, caching, template inheritance and much more. Whilst abstractions like Jade certainly aren't for everyone, our practical will cover working both with and without it.
  843. ###Practical
  844. For this practical, we're going to once again look at extending the popular Backbone Todo application. Rather than relying on localStorage for data persistence, we're going to switch to storing Todos in a MongoDB document-store instead. The code for this practical can be found in `practicals\stacks\option2`
  845. **app.js**
  846. (See [here](https://github.com/addyosmani/backbone-boilerplates/blob/master/option2/app.js) for the source)
  847. We must first include the node dependencies required by our application. These are Express, Mongoose and Path (a module containing utilities for dealing with file paths.
  848. ```javascript
  849. var application_root = __dirname,
  850. express = require("express"),
  851. path = require("path"),
  852. mongoose = require('mongoose');
  853. ```
  854. Next, create a new Express server. `express.createServer()` is a simple way of creating an instance of express.HTTPServer, which we'll be using to pass in our routes.
  855. ```javascript
  856. var app = express.createServer();
  857. ```
  858. After this, connect Mongoose up to a database (in our case, localhost should suffice). Should you require the ability to pass in authentication information, here's a sample containing all of the supported URL parameters: `mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]`
  859. ```javascript
  860. mongoose.connect('mongodb://localhost/my_database');
  861. ```
  862. A Mongoose model for any Todo item can now be easily defined by passing a schema instance to `mongoose.model`. In our case the schema covers a Todo item's `text` content, its `done` state and `order` position in the overall Todo list.
  863. ```javascript
  864. var Todo = mongoose.model('Todo', new mongoose.Schema({
  865. text: String,
  866. done: Boolean,
  867. order: Number
  868. }));
  869. ```
  870. The `configure()` methods allows us to setup what we need for the current environment with our Express server. Note that lower down in the configuration are two view/view related lines. The last one explicitly sets the viewing/templating engine to be used as Jade `app.set('view engine', 'jade')`. We can avoid these if we wish to use plain HTML/JS for our templates instead.
  871. ```javascript
  872. app.configure(function(){
  873. // the bodyParser middleware parses JSON request bodies
  874. app.use(express.bodyParser());
  875. app.use(express.methodOverride());
  876. app.use(app.router);
  877. app.use(express.static(path.join(application_root, "public")));
  878. app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  879. app.set('views', path.join(application_root, "views"));
  880. app.set('view engine', 'jade')
  881. });
  882. ```
  883. Should you prefer to switch out Jade for an alternative view engine, this can be done fairly trivially. See the section under 'Templating' here:
  884. https://github.com/joyent/node/wiki/modules. For example, to switch to EJS, you would simply write `app.set('view engine', 'ejs')`
  885. Express makes use of common HTTP verbs (get, put, post etc.) to provide easy to use, expressive routing API based on CRUD (Create, Read, Update and Delete). Below for example, we can define what happens when the browser requests the root '/'. As a trivial route in this application, it doesn't do anything particularly exciting, however getters typically read or retrieve data.
  886. ```javascript
  887. app.get('/', function(req, res){
  888. res.send('Hello World');
  889. });
  890. ```
  891. Onto something a little more useful and in our next route, navigating to '/todo' will actually render our Jade view 'todo.jade', as seen in the callback. Additional configuration values can be passed as the second parameter, such as the custom title specified below.
  892. ```javascript
  893. app.get('/todo', function(req, res){
  894. res.render('todo', {title: "Our sample application"});
  895. });
  896. ```
  897. Next, we can see the first of our '/api/' routes.
  898. ```javascript
  899. app.get('/api/todos', function(req, res){
  900. return Todo.find(function(err, todos) {
  901. return res.send(todos);
  902. });
  903. });
  904. ```
  905. The callback to our next route supports querying for todos based on a specific ID. The route string itself (once compiled) will be converted from '/api/todos/:id' to a regular expression. As you might have guessed, this is a hint that routes can also be regular expression literals if we wished to do something more complex.
  906. ```javascript
  907. app.get('/api/todos/:id', function(req, res){
  908. return Todo.findById(req.params.id, function(err, todo) {
  909. if (!err) {
  910. return res.send(todo);
  911. }
  912. });
  913. });
  914. ```
  915. Similarly, we want to support updating todos based on a specific ID as well. The following allows us to query a todo by ID and then update the values of it's three attributes (text, done, order) easily.
  916. ```javascript
  917. app.put('/api/todos/:id', function(req, res){
  918. return Todo.findById(req.params.id, function(err, todo) {
  919. todo.text = req.body.text;
  920. todo.done = req.body.done;
  921. todo.order = req.body.order;
  922. return todo.save(function(err) {
  923. if (!err) {
  924. console.log("updated");
  925. }
  926. return res.send(todo);
  927. });
  928. });
  929. });
  930. ```
  931. We've so far covered requesting todos and updating them, but a core part of the application requires us to insert (or add) new todos to our data-store. Below we can create new <code>Todo</code> models and simply save them.
  932. ```javascript
  933. app.post('/api/todos', function(req, res){
  934. var todo;
  935. todo = new Todo({
  936. text: req.body.text,
  937. done: req.body.done,
  938. order: req.body.order
  939. });
  940. todo.save(function(err) {
  941. if (!err) {
  942. return console.log("created");
  943. }
  944. });
  945. return res.send(todo);
  946. });
  947. ```
  948. We of course also want to support deleting todos (e.g if a todo has been 'cleared', it should be deleted). This also works based on a specific todo ID.
  949. ```javascript
  950. app.delete('/api/todos/:id', function(req, res){
  951. return Todo.findById(req.params.id, function(err, todo) {
  952. return todo.remove(function(err) {
  953. if (!err) {
  954. console.log("removed");
  955. return res.send('')
  956. }
  957. });
  958. });
  959. });
  960. ```
  961. Finally, this last line is to ensure we're only listening on the port app.js is running.
  962. ```javascript
  963. app.listen(3000);
  964. ```
  965. **script.js - updating our Backbone.js app**
  966. In the `/public/js` folder of options 1 (HTML templates) and 2 (Jade) for the practical, you'll find a version of the Backbone Todo app originally by Jerome Gravel-Niquet. Let's pay attention to [script.js](https://github.com/addyosmani/backbone-boilerplates/blob/master/option2/public/js/script.js). In order to change the application to work with our new back-end, we'll need to make some very minor changes to this.
  967. Reviewing `window.TodoList` (a Backbone Collection), you'll notice that it has a property called `localStorage`, which uses the Backbone [localStorage](https://github.com/jeromegn/Backbone.localStorage) adapter in order to facilitate storing data using the browser's localStorage features.
  968. ```javascript
  969. window.TodoList = Backbone.Collection.extend({
  970. // Reference to this collection's model.
  971. model: Todo,
  972. // Save all of the todo items under the `"todos"` namespace.
  973. // Typically, this should be a unique name within your application
  974. localStorage: new Store("todos"),
  975. ```
  976. In order to switch it over to our RESTful backend, we're going to make use of the `url` property or function on a collection to reference its location on the server. Models inside of a collection then use `url` to construct URLs of their own. As all of the CRUD for our RESTful API works on the base route '/api/todos', this is the value we set `url` to.
  977. ```javascript
  978. // localStorage: new Store("todos"),
  979. url: '/api/todos',
  980. ```
  981. This is the only change necessary to our existing Backbone application in order to get things working. Pretty easy, right?
  982. **todo.jade**
  983. The Jade templates for our application cover declarative markup for both the index (layout.jade) of the application and the main Todo container (todo.jade). It also covers the script-tag templates used for rendering each new Todo item that's added.
  984. ```html
  985. // Todo App Interface
  986. #todoapp
  987. .title
  988. h1 Todos
  989. .content
  990. #create-todo
  991. input#new-todo(placeholder=&quot;What needs to be done?&quot;, type=&quot;text&quot;)
  992. span.ui-tooltip-top(style=&quot;display:none;&quot;) Press Enter to save this task
  993. #todos
  994. ul#todo-list
  995. #todo-stats
  996. // Templates
  997. script#item-template(type=&quot;text/template&quot;)
  998. &lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
  999. .display
  1000. &lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
  1001. .todo-text
  1002. span#todo-destroy
  1003. .edit
  1004. input.todo-input(type=&quot;text&quot;, &quot;value&quot;=&quot;&quot;)
  1005. &lt;/div&gt;
  1006. script#stats-template(type=&quot;text/template&quot;)
  1007. &lt;% if (total) { %&gt;
  1008. span.todo-count
  1009. span.number &lt;%= remaining %&gt;
  1010. span.word &lt;%= remaining == 1 ? 'item' : 'items' %&gt;
  1011. | left.
  1012. &lt;% } %&gt;
  1013. &lt;% if (done) { %&gt;
  1014. span.todo-clear
  1015. a(href=&quot;#&quot;)
  1016. | Clear
  1017. span.number-done &lt;%= done %&gt;
  1018. | completed
  1019. span.word-done &lt;%= done == 1 ? 'item' : 'items' %&gt;
  1020. &lt;% } %&gt;
  1021. ```
  1022. **layout.jade**
  1023. ```html
  1024. !!! 5
  1025. //if lt IE 6
  1026. &lt;html class=&quot;no-js ie6 oldie&quot; lang=&quot;en&quot;&gt;
  1027. //if IE 7
  1028. &lt;html class=&quot;no-js ie7 oldie&quot; lang=&quot;en&quot;&gt;
  1029. //if IE 8
  1030. &lt;html class=&quot;no-js ie8 oldie&quot; lang=&quot;en&quot;&gt;
  1031. //if gt IE 8
  1032. &lt;!--&gt; &lt;html class=&quot;no-js&quot; lang=&quot;en&quot;&gt; &lt;!--
  1033. head
  1034. meta(charset=&quot;utf-8&quot;)
  1035. meta(http-equiv=&quot;X-UA-Compatible&quot;, content=&quot;IE=edge,chrome=1&quot;)
  1036. title=title
  1037. meta(name=&quot;description&quot;, content=&quot;&quot;)
  1038. meta(name=&quot;author&quot;, content=&quot;&quot;)
  1039. meta(name=&quot;viewport&quot;, content=&quot;width=device-width,initial-scale=1&quot;)
  1040. // CSS concatenated and minified via ant build script
  1041. link(rel=&quot;stylesheet&quot;, href=&quot;css/style.css&quot;)
  1042. // end CSS
  1043. script(src=&quot;js/libs/modernizr-2.0.6.min.js&quot;)
  1044. body
  1045. #container
  1046. header
  1047. #main(role=&quot;main&quot;)!=body
  1048. footer
  1049. //! end of #container
  1050. script(src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js&quot;)
  1051. script
  1052. window.jQuery || document.write('&lt;script src=&quot;js/libs/jquery-1.6.2.min.js&quot;&gt;&lt;\\/script&gt;')
  1053. // scripts concatenated and minified via ant build script
  1054. script(src=&quot;js/mylibs/underscore.js&quot;)
  1055. script(src=&quot;js/mylibs/backbone.js&quot;)
  1056. script(defer, src=&quot;js/plugins.js&quot;)
  1057. script(defer, src=&quot;js/script.js&quot;)
  1058. // end scripts
  1059. // Change UA-XXXXX-X to be your site's ID
  1060. script
  1061. window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
  1062. Modernizr.load({load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'});
  1063. //if lt IE 7
  1064. script(src=&quot;//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js&quot;)
  1065. script
  1066. window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})
  1067. &lt;/html&gt;
  1068. ```
  1069. **static.html**
  1070. Alternatively, a static version of our index which doesn't rely on Jade can be put together as follows. See [here](https://github.com/addyosmani/backbone-boilerplates/blob/master/option1/public/static.html) for the complete file or below for a sample.
  1071. ```html
  1072. &lt;div id=&quot;container&quot;&gt;
  1073. &lt;div id=&quot;main&quot; role=&quot;main&quot;&gt;
  1074. &lt;!-- Todo App Interface--&gt;
  1075. &lt;div id=&quot;todoapp&quot;&gt;
  1076. &lt;div class=&quot;title&quot;&gt;
  1077. &lt;h1&gt;Todos&lt;/h1&gt;
  1078. &lt;/div&gt;
  1079. &lt;div class=&quot;content&quot;&gt;
  1080. &lt;div id=&quot;create-todo&quot;&gt;
  1081. &lt;input id=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; type=
  1082. &quot;text&quot; /&gt;&lt;span style=&quot;display:none;&quot; class=&quot;ui-tooltip-top&quot;&gt;Press Enter to
  1083. save this task&lt;/span&gt;
  1084. &lt;/div&gt;
  1085. &lt;div id=&quot;todos&quot;&gt;
  1086. &lt;ul id=&quot;todo-list&quot;&gt;&lt;/ul&gt;
  1087. &lt;/div&gt;
  1088. &lt;div id=&quot;todo-stats&quot;&gt;&lt;/div&gt;
  1089. &lt;/div&gt;
  1090. &lt;/div&gt;
  1091. &lt;!-- Templates--&gt;
  1092. &lt;script id=&quot;item-template&quot; type=&quot;text/template&quot;&gt;
  1093. &lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
  1094. &lt;div class=&quot;display&quot;&gt;&lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
  1095. &lt;div class=&quot;todo-text&quot;&gt;&lt;/div&gt;&lt;span id=&quot;todo-destroy&quot;&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;edit&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; class=&quot;todo-input&quot;/&gt;&lt;/div&gt;&lt;/div&gt;
  1096. &lt;/script&gt;
  1097. &lt;script id=&quot;stats-template&quot; type=&quot;text/template&quot;&gt;
  1098. &lt;% if (total) { %&gt;
  1099. &lt;span class=&quot;todo-count&quot;&gt;&lt;span class=&quot;number&quot;&gt;&lt;%= remaining %&gt; &lt;/span&gt;&lt;span class=&quot;word&quot;&gt;&lt;%= remaining == 1 ? 'item' : 'items' %&gt;&lt;/span&gt; left.
  1100. &lt;/span&gt;&lt;% } %&gt;
  1101. &lt;% if (done) { %&gt;
  1102. &lt;span class=&quot;todo-clear&quot;&gt;&lt;a href=&quot;#&quot;&gt; Clear
  1103. &lt;span class=&quot;number-done&quot;&gt;&lt;%= done %&gt;&lt;/span&gt; completed
  1104. &lt;span class=&quot;word-done&quot;&gt;&lt;%= done == 1 ? 'item' : 'items' %&gt;&lt;/span&gt;&lt;/a&gt;&lt;/span&gt;&lt;% } %&gt;
  1105. &lt;/script&gt;
  1106. &lt;/div&gt;
  1107. &lt;/div&gt;
  1108. &lt;!--! end of #container--&gt;
  1109. ```
  1110. ### Practical Setup
  1111. We've now gone through the major points of developing a RESTful backend using Node.js, Express and Mongoose. Next, let's make sure you can get your environment setup to run the updated Todo app.
  1112. ####MongoDB
  1113. Once you've downloaded [MongoDB](http://www.mongodb.org/downloads), you'll need to complete two steps to get it up and running.
  1114. **Data directories**
  1115. MongoDB stores data in the bin/data/db folder but won't actually create this directory for you. Navigate to where you've downloaded and extracted MongoDB and run the following from terminal:
  1116. ```html
  1117. sudo mkdir -p /data/db/
  1118. sudo chown `id -u` /data/db
  1119. ```
  1120. **Running and connecting to your server**
  1121. Once this is done, open up two terminal windows.
  1122. In the first, `cd` to your MongoDB bin directory or type in the complete path to it. You'll need to start <cpde>mongod`.
  1123. ```html
  1124. $ ./bin/mongod
  1125. ```
  1126. Next, in the second terminal, start the `mongo</code shell which will connect up to localhost by default.
  1127. ```html
  1128. $ ./bin/mongo
  1129. ```
  1130. That's it!.
  1131. ####Express and Mongoose
  1132. Option 1 (HTML) and Option 2 (Jade) of the practical download both come with an install.sh bash script. This allows you to easily install Express, Mongoose, Jade (and optionally MongoDB if you prefer to) through npm (the node package manager).
  1133. * Make sure you have Node.js installed. If not, you can grab it [here](http://nodejs.org/#download)
  1134. * Next run `$ ./install.sh` at the terminal to install the rest of our dependencies. To see the exact contents of the install.sh file, see below:
  1135. **install.sh**
  1136. ```html
  1137. #!/bin/bash
  1138. npm install express
  1139. npm install mongodb --mongodb:native
  1140. npm install mongoose
  1141. npm install jade
  1142. ```
  1143. * After you've installed all of the dependencies for the stack, we can get to cloning the repo containing our practicals and running them. Start by running the below lines:
  1144. ```html
  1145. git clone git://github.com/addyosmani/backbone-boilerplates.git
  1146. cd option2
  1147. node app.js
  1148. ```
  1149. For option1 (without Jade), simply cd into option1 and run `node app.js` from there.
  1150. Finally, either of the example apps can now be accessed by navigating to:
  1151. * Option 1: `http://localhost:3000/static.html`
  1152. * Option 2: `http://localhost:3000/todo`
  1153. That's it! Whilst there's a lot more than can be done to expand on the concepts covered so far, the base we're reviewed should be enough to get you up and running with this stack if you wish to use it with Backbone.
  1154. #<a name="stack2">Building Backbone.js Apps With Ruby, Sinatra, MongoDB and Haml</a>
  1155. ##Introduction
  1156. In this chapter we're going to explore writing Backbone.js applications with a Ruby back-end. To assist with this, we're going to use [Sinatra](http://www.sinatrarb.com/) - a DSL (domain specific language) for rapidly creating web applications in Ruby. Similar to the [section](https://github.com/addyosmani/backbone-fundamentals/#stack1) on writing an application with Node.js, our server-side language (Ruby) will be used to power an API whilst Backbone.js will be the client consuming it.
  1157. ## What Is Sinatra?
  1158. In the past, you've likely come across or used [Ruby on Rails](http://rubyonrails.org) (RoR) - a popular web application framework for the Ruby programming language that helps organize applications using the MVC pattern. Sinatra is a much smaller, more light-weight alternative to it.
  1159. Whilst a very basic Rails application may require a more strict project structure (such as requiring the use of controllers, views and routing etc.), Sinatra doesn't require as many of these dependencies, sacrificing the helpers needed to connect to databases, tools to create forms or any of the other utilities Rails comes with out of the box.
  1160. What Sinatra does have is a **minimal** set of features most useful for tying specific URLs and RESTful HTTP actions to blocks of Ruby code and returning this code's output as a response. Sinatra is particularly useful for getting projects up and running quickly where we don't have a need for the extra pieces RoR provides.
  1161. For those who are familiar with more Rails, you probably know that it requires a separate routes file to define how an application should be responding to requests. These are then piped into the relevant models and controllers as needed.
  1162. Sinatra takes a more straight-forward approach, providing us with the most simple path to handling routing. By declaring ```get```,```post```, ```put``` or ```delete``` actions, we can inform Sinatra to add a new route, which we can then have respond to requests.
  1163. The framework is particularly useful for writing APIs, widgets and small-scale applications that can power the backend of a client-heavy application. As mentioned, we will be using it to power our API.
  1164. ## Getting Started With Sinatra
  1165. Let's review how to write and run a very basic Sinatra application. As most programming languages and frameworks typically start with some variation of "Hello World", we'll start with a similar example.
  1166. Note: Before beginning this section, I recommend installing Sinatra on your system. A guide to doing this can be found in the [prerequisites](#preq) section lower down in the article.
  1167. ###Routes
  1168. As mentioned, Sinatra allows us to define new routes using HTTP actions. Semantically, a route follows quite a simple structure:
  1169. ```ruby
  1170. <a HTTP action> <the desired route> do
  1171. # some behaviour
  1172. end
  1173. ```
  1174. A tiny route that outputs a "Hello World"-like message when we attempt to "get" the root could thus be written as follows:
  1175. ```ruby
  1176. require 'sinatra'
  1177. get '/' do
  1178. "Hello World! Is it me you're looking for?"
  1179. end
  1180. ```
  1181. To run this snippet, we can can simply save it to a local '.rb' file and execute it as follows:
  1182. ```ruby
  1183. ruby -rubygems example.rb
  1184. ```
  1185. If we now navigated to http://localhost:4567 in our browser we could now see the application running successfully.
  1186. The HTTP verbs we commonly work with when writing RESTful web services are: `get`, `post`, `delete` and `put`. As we now know, all Sinatra routes are basically HTTP actions (```get`` etc.) that are paired with a URL-matching pattern. We associate a pair of an action and route with code we would like sent back to the browser (executed)if the route is reached. Sinatra doesn't enforce much in the way of architectural structure, instead relying on simplicity to supporting writing powerful APIs.
  1187. Here's an example of a skeleton service we could put together supporting four common HTTP actions:
  1188. ruby
  1189. ```
  1190. get '/items' do
  1191. # list all items available
  1192. end
  1193. get '/item/:id' do
  1194. # get a single item
  1195. end
  1196. post '/item' do
  1197. # create a new item
  1198. end
  1199. put '/item/:id' do
  1200. # update an existing item
  1201. end
  1202. delete '/item/:id' do
  1203. # delete an item
  1204. end
  1205. ```
  1206. Sinatra's routing is both easy for beginners to get started with but is also flexible enough for those wishing to define more complex routes. As you probably noticed in the above example, routes can include named parameters (e.g ```/item/:id```). We can actually access the content of these routes using the ```params``` hash as follows:
  1207. ```ruby
  1208. get '/item/:id' do
  1209. # this matches "GET /item/10" and "GET /item/11"
  1210. # params[:id] is "10" or "11"
  1211. "You reached #{params[:id]}"
  1212. end
  1213. ```
  1214. Sinatra also supports route matching via splats, wildcards and regular expressions. For more information on this I recommend reading the official [docs](http://www.sinatrarb.com/documentation). Let's now take a look at handlers.
  1215. Sinatra includes convenient handler methods for tasks such as redirection, halting and passing.
  1216. ####Redirection
  1217. A simple route supporting redirection which returns a 302 response can be written as follows:
  1218. ```ruby
  1219. get '/items' do
  1220. redirect '/items/welcome'
  1221. end
  1222. ```
  1223. And if we wish to pass additional parameters such as arguments we can do so like this:
  1224. redirect 'http://site.com/', 'Oops! I think we have a problem!'
  1225. ####Halting
  1226. To immediately stop a request (halting) we can use 'halt'. Heres an example of halting a request where we specify the message body:
  1227. ```halt "who goes there!?"```
  1228. ####Passing
  1229. 'Passing' is the concept of deferring processing of a block to the next matching route. We do this using `pass`. In the following example if a parameter isnt the username we expect (rick-astley) we simply pass it on:
  1230. ```ruby
  1231. get '/members/:username' do
  1232. pass unless params[:username] == 'rick-astley'
  1233. 'Never gonna give you up, never gonna let you down'
  1234. end
  1235. get '/member/*' do
  1236. 'Welcome!'
  1237. end
  1238. ```
  1239. There are also handler methods that can assist with sessions (specifically, cookie-based session handling). To use Sinatra's session handling, first enable it in your application with:
  1240. ```ruby
  1241. enable :sessions
  1242. ```
  1243. You can then use the session handling capabilities as follows:
  1244. ```ruby
  1245. get '/items' do
  1246. session['visitCounter'] ||= 0;
  1247. session['visitCounter'] += 1;
  1248. "This page has been accessed #{session['visitCounter']} times"
  1249. end
  1250. ```
  1251. Note: By default enable:sessions will store all data in cookies. If this is not desired, you can not call this and instead use some Rack middleware instead. For more on this see [here](http://www.sinatrarb.com/intro#Using%20Sessions).
  1252. This only touches the surface of what can be done using routes and handlers, but is sufficient for us to write the Sinatra-powered API service we require in the practical section of this chapter.
  1253. ##Templating And HAML
  1254. Let's now discuss templating.Out of the box, we can begin using templates in our Sinatra applications with ERB. ERB is included with Ruby and allows Ruby code to be added to any plain text document for the purpose of generating information or flow control. In the following example using an ERB template, note that views are by default located in the ```views``` directory of our application.
  1255. ```ruby
  1256. get '/items' do
  1257. erb :default
  1258. # renders views/default.erb
  1259. end
  1260. ```
  1261. A useful Sinatra convention worth noting is how layouts are handled. Layouts automatically search for a views/layout template which is rendered before any other views are loaded. With ERB, our views/layout.erb file could look as follows:
  1262. ```html
  1263. <html>
  1264. <head></head>
  1265. <body>
  1266. <%= data %>
  1267. </body>
  1268. </html>
  1269. ```
  1270. Haml is a popular alternative to ERB which offers an abstract syntax for writing application templates. It has been said to be:
  1271. * Straight-forward to learn
  1272. * Very easy to read and use for visually expressing a hierarchy of DOM elements
  1273. * Popular with web designers as it builds on top of CSS syntax
  1274. * Well documented with a large community backing it
  1275. * Almost as fast as ERB
  1276. For the purpose of comparison, below we can see an ERB template compared to it's Haml equivalent.
  1277. ####ERB
  1278. ```html
  1279. <div class="todo" id="content">
  1280. <h2 class="entry_title"><%= h @todo.title %></h2>
  1281. <div class="entry_link"><%= link_to('link', @todo.link) %></div>
  1282. </div>
  1283. ```
  1284. ####Haml
  1285. ```html
  1286. .todo#content
  1287. %h2.entry_title= @todo.title
  1288. .entry_link= link_to('link', @todo.link)
  1289. ```
  1290. One of the first things we notice is that the Haml snippet looks significantly more like CSS than it does traditional markup. It's much easier to read and we no longer need to be concerned with divs, spans, closing tags or other semantic rules that usually mean more keystrokes. The approach taken to making whitespace a part of the syntax also means it can be much easier to compare changes between multiple documents (especially if you're doing a diff).
  1291. In the list of Haml features, we briefly mentioned web designers. As developers, we regularly need to communicate and work with designers, but we always have to remember that at the end of the day, they are not programmers. They're usually more concerned with the look and the feel of an application, but if we want them to write mark-up as a part of the templates or skins they create, Haml is a simpler option that has worked well for teams at a number of companies.
  1292. ```ruby
  1293. %h1 This is some h1 text
  1294. %h2 This is some h2 text.
  1295. %p Now we have a line containing a single instance variable: @content
  1296. %p= @content
  1297. %p Embedding Ruby code in the middle of a line can be done using ==.
  1298. %p== Here is an example: #{@foobar}
  1299. %p We can also add attributes using {}
  1300. %p{:style => "color:green"} We just made this paragraph green!
  1301. %p You'll want to apply classes and ids to your DOM, too.
  1302. %p.foo This has the foo class
  1303. %p.bar This has the bar class
  1304. %p#foobar This has the foobar id
  1305. %p.foo#foobar Or you can combine them!
  1306. %p Nesting can be done like this
  1307. %p
  1308. Or even like this
  1309. ```
  1310. Note: Haml is whitespace sensitive and will not correctly work if it isn't indented by an even number of spaces. This is due to whitespace being used for nesting in place of the classic HTML markup approach of closing tags.
  1311. #MongoDB Ruby Driver
  1312. ##Getting started
  1313. Once the MongoDB Ruby driver is installed, we can begin to use it to connect to a Mongo database. To create a connection using localhost, we simply specify the driver as a dependency. Assuming we're using the default port we can then connect as follows:
  1314. ```ruby
  1315. require 'mongo'
  1316. # where 'learning-mongo' is the name of our database:
  1317. db = Connection.new.db('learning-mongo');
  1318. ```
  1319. We probably also want to place some data into 'learning-mongo'. It could be as simple as a note, so why don't we go ahead and begin a notes collection?:
  1320. ```ruby
  1321. notes = db.collection('notes')
  1322. ```
  1323. Something interesting worth noting is that at this point, we haven't actually created the database nor the collection we're referencing above.
  1324. Neither of these items exist in Mongo (just yet) but as we're working with a new database but they will once we insert some real data.
  1325. A new note could be defined using key/value pairs as follows and then inserted into 'learning-mongo' using `collection.insert()`:
  1326. ```ruby
  1327. our_note = { :text => 'Remember the milk', :remindInterval => 'weekly'}
  1328. note_id = notes.insert(our_note)
  1329. ```
  1330. What is returned from inserting a note into the notes collection is an `ObjectId` reference for the note from Mongo. This is useful as we can re-use it to locate the same document in our database.
  1331. ```ruby
  1332. note = notes.find( :id => note_id ).first
  1333. ```
  1334. This can also be used in conjunction with Mongo's `collection.update()` method and [query](http://www.mongodb.org/display/DOCS/Updating) operators (i.e `$set`) to replace fields in an existing document.
  1335. We might update an entire document as follows:
  1336. ```ruby
  1337. note = notes.find( :id => note_id ).first
  1338. note[:text] = 'Remember the bread'
  1339. notes.update({ :_id => note_id }, note)
  1340. ```
  1341. or using `$set`, update an existing document without overwriting the entire object as like this:
  1342. ```ruby
  1343. notes.update({ :_id => note_id }, '$set' => { :text = > 'Remember the bread' })
  1344. ```
  1345. Useful to know: Almost each MongoDB document has an _id field as it's first attribute. This can normally
  1346. be of any type, however a special BSON datatype is provided for object ids. It's a
  1347. 12-byte binary value that has a high probability of being unique when allocated.
  1348. Note: Whilst we opted for the MongoDB Ruby Driver for this stack, you may also be interested in **DataMapper** - a solution which allows us to use the same API to talk to a number of different datastores. This works well for both relational and non-relational databases and more information is available on the official [project page](http://datamapper.org/why.html). [Sinatra: The Book](http://sinatra-book.gittr.com/#datamapper) also contains a brief tutorial on DataMapper for anyone interested in exploring it further.
  1349. #Practical
  1350. We're going to use Sinatra in a similar manner to how we used Express in the last chapter. It will power a RESTful API supporting CRUD operations. Together with a MongoDB data store, this will allow us to easily persist data (todo items) whilst ensuring they are stored in a database. If you've read the previous chapter or have gone through any of the Todo examples covered so far, you will find this surprisingly straight-forward.
  1351. Remember that the default Todo example included with Backbone.js already persists data, although it does this via a localStorage adapter. Luckily there aren't a great deal of changes needed to switch over to using our Sinatra-based API. Let's briefly review the code that will be powering the CRUD operations for this sections practical, as we go course won't be starting off with a near-complete base for most of our real world applications.
  1352. ###<a id="preq">Installing The Prerequisites</a>
  1353. ####Ruby
  1354. If using OSX or Linux, Ruby may be one of a number of open-source packages that come pre-installed and you can skip over to the next paragraph. In case you would like to check if check if you have Ruby installed, open up the terminal prompt and type:
  1355. ```$ ruby -v```
  1356. The output of this will either be the version of Ruby installed or an error complaining that Ruby wasn't found.
  1357. Should you need to install Ruby manually (e.g for an operating system such as Windows), you can do so by downloading the latest version from http://www.ruby-lang.org/en/downloads/. Alternatively, (RVM)[http://beginrescueend.com/rvm/install/] (Ruby Version Manager) is a command-line tool that allows you to easily install and manage multiple ruby environments with ease.
  1358. ####Ruby Gems
  1359. Next, we will need to install Ruby Gems. Gems are a standard way to package programs or libraries written in Ruby and with Ruby Gems it's possible to install additional dependencies for Ruby applications very easily.
  1360. On OSX, Linux or Windows go to [http://rubyforge.org/projects/rubygems](http://rubyforge.org/projects/rubygems) and download the latest version of Ruby Gems. Once downloaded, open up a terminal, navigate to the folder where this resides and enter:
  1361. ```
  1362. $> tar xzvf rubygems.tgz
  1363. $> cd rubygems
  1364. $> sudo ruby setup.rb
  1365. ```
  1366. There will likely be a version number included in your download and you should make sure to include this when tying the above. Finally, a symlink (symbolic link) to tie everything togther should be fun as follows:
  1367. ```$ sudo ln -s /usr/bin/gem1.8.17 /usr/bin/gem```
  1368. To check that Ruby Gems has been correctly installed, type the following into your terminal:
  1369. ```
  1370. $ gem -v
  1371. ```
  1372. ####Sinatra
  1373. With Ruby Gems setup, we can now easily install Sinatra. For Linux or OSX type this in your terminal:
  1374. ```$ sudo gem install sinatra```
  1375. and if you're on Windows, enter the following at a command prompt:
  1376. ```c:\\ > gem install sinatra```
  1377. ####Haml
  1378. As with other DSLs and frameworks, Sinatra supports a wide range of different templating engines. [ERB](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html) is the one most often recommended by the Sinatra camp, however
  1379. as a part of this chapter, we're going to explore the use of [Haml](http://haml.hamptoncatlin.com/) to define our application templates.
  1380. Haml stands for HTML Abstractional Markup Language and is a lightweight markup language abstraction that can be used to describe HTML without the need to use traditional markup language semantics (such as opening and closing tags).
  1381. Installing Haml can be done in just a line using Ruby Gems as follows:
  1382. ```$ gem install haml```
  1383. ####MongoDB
  1384. If you haven't already downloaded and installed MongoDB from an earlier chapter, please [do so](http://www.mongodb.org/downloads) now. With Ruby Gems, Mongo can be installed in just one line:
  1385. ```$ gem install mongodb```
  1386. We now require two further steps to get everything up and running.
  1387. #####1.Data directories
  1388. MongoDB stores data in the bin/data/db folder but won't actually create this directory for you. Navigate to where you've downloaded and extracted Mongo and run the following from terminal:
  1389. ```
  1390. sudo mkdir -p /data/db/
  1391. sudo chown `id -u` /data/db
  1392. ```
  1393. #####2.Running and connecting to your server
  1394. Once this is done, open up two terminal windows.
  1395. In the first, cd to your MongoDB bin directory or type in the complete path to it. You'll need to start mongod.
  1396. ```
  1397. $ ./bin/mongod
  1398. ```
  1399. Finally, in the second terminal, start the mongo shell which will connect up to localhost by default.
  1400. ```
  1401. $ ./bin/mongo
  1402. ```
  1403. ####MongoDB Ruby Driver
  1404. As we'll be using the [MongoDB Ruby Driver](https://github.com/mongodb/mongo-ruby-driver), we'll also require the following gems:
  1405. The gem for the driver itself:
  1406. ```
  1407. $ gem install mongo
  1408. ```
  1409. and the driver's other prerequisite, bson:
  1410. ```
  1411. $ gem install bson_ext
  1412. ```
  1413. This is basically a collection of extensions used to increase serialization speed.
  1414. That's it for our prerequisites!.
  1415. ##Tutorial
  1416. To get started, let's get a local copy of the practical application working on our system.
  1417. ###Application Files
  1418. Clone [this](http://github.com/addyosmani/backbone-fundamentals) repository and navigate to `/practicals/stacks/option3`. Now run the following lines at the terminal:
  1419. ```
  1420. ruby app.rb
  1421. ```
  1422. Finally, navigate to <code>http://localhost:4567/todo</code> to see the application running successfully.
  1423. **Note:** The Haml layout files for Option 3 can be found in the /views folder.
  1424. The directory structure for our practical application is as follows:
  1425. ```
  1426. --public
  1427. ----css
  1428. ----img
  1429. ----js
  1430. -----script.js
  1431. ----test
  1432. --views
  1433. app.rb
  1434. ```
  1435. The `public` directory contains the scripts and stylesheets for our application and uses HTML5 Boilerplate as a base. You can find the Models, Views and Collections for this section within ```public/js/scripts.js``` (however, this can of course be expanded into sub-directories for each component if desired).
  1436. ```scripts.js``` contains the following Backbone component definitions:
  1437. ```
  1438. --Models
  1439. ----Todo
  1440. --Collections
  1441. ----TodoList
  1442. --Views
  1443. ---TodoView
  1444. ---AppView
  1445. ```
  1446. `app.rb` is the small Sinatra application that powers our backend API.
  1447. Lastly, the `views` directory hosts the Haml source files for our application's index and templates, both of which are compiled to standard HTML markup at runtime.
  1448. These can be viewed along with other note-worthy snippets of code from the application below.
  1449. ###Backbone
  1450. ####Views
  1451. In our main application view (AppView), we want to load any previously stored Todo items in our Mongo database when the view initializes. This is done below with the line ```Todos.fetch()``` in the ``initialize()`` method where we also bind to the relevant events on the `Todos` collection for when items are added or changed.
  1452. ```javascript
  1453. // Our overall **AppView** is the top-level piece of UI.
  1454. var AppView = Backbone.View.extend({
  1455. // Instead of generating a new element, bind to the existing skeleton of
  1456. // the App already present in the HTML.
  1457. el: $("#todoapp"),
  1458. // Our template for the line of statistics at the bottom of the app.
  1459. statsTemplate: _.template($('#stats-template').html()),
  1460. // Delegated events for creating new items, and clearing completed ones.
  1461. events: {
  1462. "keypress #new-todo": "createOnEnter",
  1463. "keyup #new-todo": "showTooltip",
  1464. "click .todo-clear a": "clearCompleted"
  1465. },
  1466. // At initialization
  1467. initialize: function() {
  1468. this.input = this.$("#new-todo");
  1469. Todos.on('add', this.addOne, this);
  1470. Todos.on('reset', this.addAll, this);
  1471. Todos.on('all', this.render, this);
  1472. Todos.fetch();
  1473. },
  1474. // Re-rendering the App just means refreshing the statistics -- the rest
  1475. // of the app doesn't change.
  1476. render: function() {
  1477. this.$('#todo-stats').html(this.statsTemplate({
  1478. total: Todos.length,
  1479. done:
  1480. .
  1481. ```
  1482. ###Collections
  1483. In the TodoList collection below, we've set the `url` property to point to `/api/todos` to reference the collection's location on the server. When we attempt to access this from our Sinatra-backed API, it should return a list of all the Todo items that have been previously stored in Mongo.
  1484. For the sake of thoroughness, our API will also support returning the data for a specific Todo item via `/api/todos/itemID`. We'll take a look at this again when writing the Ruby code powering our backend.
  1485. ```javascript
  1486. // Todo Collection
  1487. var TodoList = Backbone.Collection.extend({
  1488. // Reference to this collection's model.
  1489. model: Todo,
  1490. // Save all of the todo items under the `"todos"` namespace.
  1491. // localStorage: new Store("todos"),
  1492. url: '/api/todos',
  1493. // Filter down the list of all todo items that are finished.
  1494. done: function() {
  1495. return this.filter(function(todo){ return todo.get('done'); });
  1496. },
  1497. // Filter down the list to only todo items that are still not finished.
  1498. remaining: function() {
  1499. return this.without.apply(this, this.done());
  1500. },
  1501. // We keep the Todos in sequential order, despite being saved by unordered
  1502. // GUID in the database. This generates the next order number for new items.
  1503. nextOrder: function() {
  1504. if (!this.length) return 1;
  1505. return this.last().get('order') + 1;
  1506. },
  1507. // Todos are sorted by their original insertion order.
  1508. comparator: function(todo) {
  1509. return todo.get('order');
  1510. }
  1511. });
  1512. ```
  1513. ###Model
  1514. The model for our Todo application remains largely unchanged from the versions previously covered in this book. It is however worth noting that calling the function `model.url()` within the below would return the relative URL where a specific Todo item could be located on the server.
  1515. ```javascript
  1516. // Our basic **Todo** model has `text`, `order`, and `done` attributes.
  1517. var Todo = Backbone.Model.extend({
  1518. idAttribute: "_id",
  1519. // Default attributes for a todo item.
  1520. defaults: function() {
  1521. return {
  1522. done: false,
  1523. order: Todos.nextOrder()
  1524. };
  1525. },
  1526. // Toggle the `done` state of this todo item.
  1527. toggle: function() {
  1528. this.save({done: !this.get("done")});
  1529. }
  1530. });
  1531. ```
  1532. ###Ruby/Sinatra
  1533. Now that we've defined our main models, views and collections let's get the CRUD operations required by our Backbone application supported in our Sinatra API.
  1534. We want to make sure that for any operations changing underlying data (create, update, delete) that our Mongo data store correctly reflects these.
  1535. ###app.rb
  1536. For `app.rb`, we first define the dependencies required by our application. These include Sinatra, Ruby Gems, the MongoDB Ruby driver and the JSON gem.
  1537. ```ruby
  1538. require 'rubygems'
  1539. require 'sinatra'
  1540. require 'mongo'
  1541. require 'json'
  1542. ```
  1543. Next, we create a new connection to Mongo, specifying any custom configuration desired. If running a multi-threaded application, setting the 'pool_size' allows us to specify a maximum pool size and 'timeout' a maximum timeout for waiting for old connections to be released to the pool.
  1544. ```ruby
  1545. DB = Mongo::Connection.new.db("mydb", :pool_size => 5, :timeout => 5)
  1546. ```
  1547. Finally we define the routes to be supported by our API. Note that in the first two blocks - one for our
  1548. application root (`/`) and the other for our todo items route `/todo` - we're using Haml for template rendering.
  1549. ```ruby
  1550. class TodoApp < Sinatra::Base
  1551. get '/' do
  1552. haml :index, :attr_wrapper => '"', :locals => {:title => 'hello'}
  1553. end
  1554. get '/todo' do
  1555. haml :todo, :attr_wrapper => '"', :locals => {:title => 'Our Sinatra Todo app'}
  1556. end
  1557. ```
  1558. `haml :index` instructs Sinatra to use the `views/index.haml` for the application index, whilst ```attr_wrapper`` is simply defining the values to be used for any local variables defined inside the template.
  1559. This similarly applies Todo items with the template `views/todo.haml'.
  1560. The rest of our routes make use of the `params` hash and a number of useful helper methods included with the MongoDB Ruby driver. For more details on these, please
  1561. read the comments I've made inline below:
  1562. ```ruby
  1563. get '/api/:thing' do
  1564. # query a collection :thing, convert the output to an array, map the _id
  1565. # to a string representation of the object's _id and finally output to JSON
  1566. DB.collection(params[:thing]).find.to_a.map{|t| from_bson_id(t)}.to_json
  1567. end
  1568. get '/api/:thing/:id' do
  1569. # get the first document with the id :id in the collection :thing as a single document (rather
  1570. # than a Cursor, the standard output) using find_one(). Our bson utilities assist with
  1571. # ID conversion and the final output returned is also JSON
  1572. from_bson_id(DB.collection(params[:thing]).find_one(to_bson_id(params[:id]))).to_json
  1573. end
  1574. post '/api/:thing' do
  1575. # parse the post body of the content being posted, convert to a string, insert into
  1576. # the collection #thing and return the ObjectId as a string for reference
  1577. oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.to_s))
  1578. "{\"_id\": \"#{oid.to_s}\"}"
  1579. end
  1580. delete '/api/:thing/:id' do
  1581. # remove the item with id :id from the collection :thing, based on the bson
  1582. # representation of the object id
  1583. DB.collection(params[:thing]).remove('_id' => to_bson_id(params[:id]))
  1584. end
  1585. put '/api/:thing/:id' do
  1586. # collection.update() when used with $set (as covered earlier) allows us to set single values
  1587. # in this case, the put request body is converted to a string, rejecting keys with the name '_id' for security purposes
  1588. DB.collection(params[:thing]).update({'_id' => to_bson_id(params[:id])}, {'$set' => JSON.parse(request.body.read.to_s).reject{|k,v| k == '_id'}})
  1589. end
  1590. # utilities for generating/converting MongoDB ObjectIds
  1591. def to_bson_id(id) BSON::ObjectId.from_string(id) end
  1592. def from_bson_id(obj) obj.merge({'_id' => obj['_id'].to_s}) end
  1593. end
  1594. ```
  1595. That's it. The above is extremely lean for an entire API, but does allow us to read and write data to support the functionality required by our client-side application.
  1596. For more on what MongoDB and the MongoDB Ruby driver are capable of, please do feel free to read their documentation for more information.
  1597. If you're a developer wishing to take this example further, why not try to add some additional capabilities to the service:
  1598. * Validation: improved validation of data in the API. What more could be done to ensure data sanitization?
  1599. * Search: search or filter down Todo items based on a set of keywords or within a certain date range
  1600. * Pagination: only return the Nth number of Todo items or items from a start and end-point
  1601. ###Haml/Templates
  1602. Finally, we move on to the Haml files that define our application index (layout.haml) and the template for a specific Todo item (todo.haml). Both of these are largely self-explanatory, but it's useful to see the differences between the Jade approach we reviewed in the last chapter vs. using Haml for this implementation.
  1603. Note: In our Haml snippets below, the forward slash character is used to indicate a comment. When this character is placed at the beginning of a line, it wraps all of the text after it into a HTML comment. e.g
  1604. ```/ These are templates```
  1605. compiles to:
  1606. ```<!-- These are templates -->```
  1607. ###index.haml
  1608. ```html
  1609. %head
  1610. %meta{'charset' => 'utf-8'}/
  1611. %title=title
  1612. %meta{'name' => 'description', 'content' => ''}/
  1613. %meta{'name' => 'author', 'content' => ''}/
  1614. %meta{'name' => 'viewport', 'content' => 'width=device-width,initial-scale=1'}/
  1615. / CSS concatenated and minified via ant build script
  1616. %link{'rel' => 'stylesheet', 'href' => 'css/style.css'}/
  1617. / end CSS
  1618. %script{'src' => 'js/libs/modernizr.min.js'}
  1619. %body
  1620. %div#container
  1621. %header
  1622. %div#main
  1623. = yield
  1624. %footer
  1625. /! end of #container
  1626. %script{'src' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'}
  1627. / scripts concatenated and minified via ant build script
  1628. %script{'src' => 'js/mylibs/underscore.js'}
  1629. %script{'src' => 'js/mylibs/backbone.js'}
  1630. %script{'defer' => true, 'src' => 'js/plugins.js'}
  1631. %script{'defer' => true, 'src' => 'js/script.js'}
  1632. / end scripts
  1633. ```
  1634. ###todo.haml
  1635. ```html
  1636. %div#todoapp
  1637. %div.title
  1638. %h1
  1639. Todos
  1640. %div.content
  1641. %div#create-todo
  1642. %input#new-todo{"placeholder" => "What needs to be done?", "type" => "text"}/
  1643. %span.ui-tooltip-top{"style" => "display:none;"} Press Enter to save this task
  1644. %div#todos
  1645. %ul#todo-list
  1646. %div#todo-stats
  1647. / Templates
  1648. %script#item-template{"type" => "text/template"}
  1649. <div class="todo <%= done ? 'done' : '' %>">
  1650. %div.display
  1651. <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
  1652. %div.todo-text
  1653. %span#todo-destroy
  1654. %div.edit
  1655. %input.todo-input{"type" => "text", "value" =>""}/
  1656. </div>
  1657. %script#stats-template{"type" => "text/template"}
  1658. <% if (total) { %>
  1659. %span.todo-count
  1660. %span.number <%= remaining %>
  1661. %span.word <%= remaining == 1 ? 'item' : 'items' %>
  1662. left.
  1663. <% } %>
  1664. <% if (done) { %>
  1665. %span.todo-clear
  1666. %a{"href" => "#"}
  1667. Clear
  1668. %span.number-done <%= done %>
  1669. completed
  1670. %span.word-done <%= done == 1 ? 'item' : 'items' %>
  1671. <% } %>
  1672. ```
  1673. ##Conclusions
  1674. In this chapter, we looked at creating a Backbone application backed by an API powered by Ruby, Sinatra, Haml, MongoDB and the MongoDB driver. I personally found developing APIs with Sinatra a relatively painless experience and one which I felt was
  1675. on-par with the effort required for the Node/Express implementation of the same application.
  1676. This section is by no means the most comprehensive guide on building complex apps using all of the items in this particular stack. I do however hope it was an introduction sufficient enough to help you decide on what stack to try out for your next project.
  1677. # <a name="advanced">Advanced</a>
  1678. ---
  1679. ##<a name="modularjs">Modular JavaScript</a>
  1680. When we say an application is modular, we generally mean it's composed of a set of highly decoupled, distinct pieces of functionality stored in modules. As you probably know, loose coupling facilitates easier maintainability of apps by removing dependencies where possible. When this is implemented efficiently, its quite easy to see how changes to one part of a system may affect another.
  1681. Unlike some more traditional programming languages however, the current iteration of JavaScript (ECMA-262) doesn't provide developers with the means to import such modules of code in a clean, organized manner. It's one of the concerns with specifications that haven't required great thought until more recent years where the need for more organized JavaScript applications became apparent.
  1682. Instead, developers at present are left to fall back on variations of the module or object literal patterns. With many of these, module scripts are strung together in the DOM with namespaces being described by a single global object where it's still possible to incur naming collisions in your architecture. There's also no clean way to handle dependency management without some manual effort or third party tools.
  1683. Whilst native solutions to these problems will be arriving in ES Harmony, the good news is that writing modular JavaScript has never been easier and you can start doing it today.
  1684. In this next part of the book, we're going to look at how to use AMD modules and RequireJS for cleanly wrapping units of code in your application into manageable modules.
  1685. ##<a name="organizingmodules">Organizing modules with RequireJS and AMD</a>
  1686. In case you haven't used it before, [RequireJS](http://requirejs.org) is a popular script loader written by James Burke - a developer who has been quite instrumental in helping shape the AMD module format, which we'll discuss more shortly. Some of RequireJS's capabilities include helping to load multiple script files, helping define modules with or without dependencies and loading in non-script dependencies such as text files.
  1687. So, why use RequireJS with Backbone? Although Backbone is excellent when it comes to providing a sanitary structure to your applications, there are a few key areas where some additional help could be used:
  1688. 1) Backbone doesn't endorse a particular approach to modular-development. Although this means it's quite open-ended for developers to opt for classical patterns like the module-pattern or Object Literals for structuring their apps (which both work fine), it also means developers aren't sure of what works best when other concerns come into play, such as dependency management.
  1689. RequireJS is compatible with the AMD (Asynchronous Module Definition) format, a format which was born from a desire to write something better than the 'write lots of script tags with implicit dependencies and manage them manually' approach to development. In addition to allowing you to clearly declare dependencies, AMD works well in the browser, supports string IDs for dependencies, declaring multiple modules in the same file and gives you easy-to-use tools to avoid polluting the global namespace.
  1690. 2) Let's discuss dependency management a little more as it can actually be quite challenging to get right if you're doing it by hand. When we write modules in JavaScript, we ideally want to be able to handle the reuse of code units intelligently and sometimes this will mean pulling in other modules at run-time whilst at other times you may want to do this dynamically to avoid a large pay-load when the user first hits your application.
  1691. Think about the GMail web-client for a moment. When users initially load up the page on their first visit, Google can simply hide widgets such as the chat module until a user has indicated (by clicking 'expand') that they wish to use it. Through dynamic dependency loading, Google could load up the chat module only then, rather than forcing all users to load it when the page first initializes. This can improve performance and load times and can definitely prove useful when building larger applications.
  1692. I've previously written [a detailed article](http://addyosmani.com/writing-modular-js) covering both AMD and other module formats and script loaders in case you'd like to explore this topic further. The takeaway is that although it's perfectly fine to develop applications without a script loader or clean module format in place, it can be of significant benefit to consider using these tools in your application development.
  1693. ###Writing AMD modules with RequireJS
  1694. As discussed above, the overall goal for the AMD format is to provide a solution for modular JavaScript that developers can use today. The two key concepts you need to be aware of when using it with a script-loader are a `define()` method for facilitating module definition and a `require()` method for handling dependency loading. `define()` is used to define named or unnamed modules based on the proposal using the following signature:
  1695. ```javascript
  1696. define(
  1697. module_id /*optional*/,
  1698. [dependencies] /*optional*/,
  1699. definition function /*function for instantiating the module or object*/
  1700. );
  1701. ```
  1702. As you can tell by the inline comments, the `module_id` is an optional argument which is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it's useful too). When this argument is left out, we call the module 'anonymous'. When working with anonymous modules, the idea of a module's identity is DRY, making it trivial to avoid duplication of filenames and code.
  1703. Back to the define signature, the dependencies argument represents an array of dependencies which are required by the module you are defining and the third argument ('definition function') is a function that's executed to instantiate your module. A barebone module (compatible with RequireJS) could be defined using `define()` as follows:
  1704. ```javascript
  1705. // A module ID has been omitted here to make the module anonymous
  1706. define(['foo', 'bar'],
  1707. // module definition function
  1708. // dependencies (foo and bar) are mapped to function parameters
  1709. function ( foo, bar ) {
  1710. // return a value that defines the module export
  1711. // (i.e the functionality we want to expose for consumption)
  1712. // create your module here
  1713. var myModule = {
  1714. doStuff:function(){
  1715. console.log('Yay! Stuff');
  1716. }
  1717. }
  1718. return myModule;
  1719. });
  1720. ```
  1721. ####Alternate syntax
  1722. There is also a [sugared version](http://requirejs.org/docs/whyamd.html#sugar) of `define()` available that allows you to declare your dependencies as local variables using `require()`. This will feel familiar to anyone who's used node, and can be easier to add or remove dependencies.
  1723. Here is the previous snippet using the alternate syntax:
  1724. ```javascript
  1725. // A module ID has been omitted here to make the module anonymous
  1726. define(function(require){
  1727. // module definition function
  1728. // dependencies (foo and bar) are defined as local vars
  1729. var foo = require('foo'),
  1730. bar = require('bar');
  1731. // return a value that defines the module export
  1732. // (i.e the functionality we want to expose for consumption)
  1733. // create your module here
  1734. var myModule = {
  1735. doStuff:function(){
  1736. console.log('Yay! Stuff');
  1737. }
  1738. }
  1739. return myModule;
  1740. });
  1741. ```
  1742. The `require()` method is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies. An example of its usage is:
  1743. ```javascript
  1744. // Consider 'foo' and 'bar' are two external modules
  1745. // In this example, the 'exports' from the two modules loaded are passed as
  1746. // function arguments to the callback (foo and bar)
  1747. // so that they can similarly be accessed
  1748. require(['foo', 'bar'], function ( foo, bar ) {
  1749. // rest of your code here
  1750. foo.doSomething();
  1751. });
  1752. ```
  1753. **Wrapping modules, views and other components with AMD**
  1754. Now that we've taken a look at how to define AMD modules, let's review how to go about wrapping components like views and collections so that they can also be easily loaded as dependencies for any parts of your application that require them. At it's simplest, a Backbone model may just require Backbone and Underscore.js. These are considered it's dependencies and so, to write an AMD model module, we would simply do this:
  1755. ```javascript
  1756. define(['underscore', 'backbone'], function(_, Backbone) {
  1757. var myModel = Backbone.Model.extend({
  1758. // Default attributes
  1759. defaults: {
  1760. content: "hello world",
  1761. },
  1762. // A dummy initialization method
  1763. initialize: function() {
  1764. },
  1765. clear: function() {
  1766. this.destroy();
  1767. this.view.remove();
  1768. }
  1769. });
  1770. return myModel;
  1771. });
  1772. ```
  1773. Note how we alias Underscore.js's instance to `_` and Backbone to just `Backbone`, making it very trivial to convert non-AMD code over to using this module format. For a view which might require other dependencies such as jQuery, this can similarly be done as follows:
  1774. ```javascript
  1775. define([
  1776. 'jquery',
  1777. 'underscore',
  1778. 'backbone',
  1779. 'collections/mycollection',
  1780. 'views/myview'
  1781. ], function($, _, Backbone, myCollection, myView){
  1782. var AppView = Backbone.View.extend({
  1783. ...
  1784. ```
  1785. Aliasing to the dollar-sign (`$`), once again makes it very easy to encapsulate any part of an application you wish using AMD.
  1786. ##<a name="externaltemplates">Keeping Your Templates External Using RequireJS And The Text Plugin</a>
  1787. Moving your [Underscore/Mustache/Handlebars] templates to external files is actually quite straight-forward. As this application makes use of RequireJS, I'll discuss how to implement external templates using this specific script loader.
  1788. RequireJS has a special plugin called text.js which is used to load in text file dependencies. To use the text plugin, simply follow these simple steps:
  1789. 1. Download the plugin from http://requirejs.org/docs/download.html#text and place it in either the same directory as your application's main JS file or a suitable sub-directory.
  1790. 2. Next, include the text.js plugin in your initial RequireJS configuration options. In the code snippet below, we assume that RequireJS is being included in our page prior to this code snippet being executed. Any of the other scripts being loaded are just there for the sake of example.
  1791. ```javascript
  1792. require.config( {
  1793. paths: {
  1794. 'backbone': 'libs/AMDbackbone-0.5.3',
  1795. 'underscore': 'libs/underscore-1.2.2',
  1796. 'text': 'libs/require/text',
  1797. 'jquery': 'libs/jQuery-1.7.1',
  1798. 'json2': 'libs/json2',
  1799. 'datepicker': 'libs/jQuery.ui.datepicker',
  1800. 'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
  1801. 'jquerymobile': 'libs/jquery.mobile-1.0'
  1802. },
  1803. baseUrl: 'app'
  1804. } );
  1805. ```
  1806. 3. When the `text!` prefix is used for a dependency, RequireJS will automatically load the text plugin and treat the dependency as a text resource. A typical example of this in action may look like..
  1807. ```javascript
  1808. require(['js/app', 'text!templates/mainView.html'],
  1809. function(app, mainView){
  1810. // the contents of the mainView file will be
  1811. // loaded into mainView for usage.
  1812. }
  1813. );
  1814. ```
  1815. 4. Finally we can use the text resource that's been loaded for templating purposes. You're probably used to storing your HTML templates inline using a script with a specific identifier.
  1816. With Underscore.js's micro-templating (and jQuery) this would typically be:
  1817. HTML:
  1818. <script type="text/template" id="mainViewTemplate">
  1819. <% _.each( person, function( person_item ){ %>
  1820. <li><%= person_item.get("name") %></li>
  1821. <% }); %>
  1822. </script>
  1823. JS:
  1824. ```javascript
  1825. var compiled_template = _.template( $('#mainViewTemplate').html() );
  1826. ```
  1827. With RequireJS and the text plugin however, it's as simple as saving your template into an external text file (say, `mainView.html`) and doing the following:
  1828. ```javascript
  1829. require(['js/app', 'text!templates/mainView.html'],
  1830. function(app, mainView){
  1831. var compiled_template = _.template( mainView );
  1832. }
  1833. );
  1834. ```
  1835. That's it!. You can then go applying your template to a view in Backbone doing something like:
  1836. ```javascript
  1837. collection.someview.$el.html( compiled_template( { results: collection.models } ) );
  1838. ```
  1839. All templating solutions will have their own custom methods for handling template compilation, but if you understand the above, substituting Underscore's micro-templating for any other solution should be fairly trivial.
  1840. **Note:** You may also be interested in looking at [Require.js tpl](https://github.com/ZeeAgency/requirejs-tpl). It's an AMD-compatible version of the Underscore templating system that also includes support for optimization (pre-compiled templates) which can lead to better performance and no evals. I have yet to use it myself, but it comes as a recommended resource.
  1841. ##<a name="optimizingrequirejs">Optimizing Backbone apps for production with the RequireJS Optimizer</a>
  1842. As experienced developers may know, an essential final step when writing both small and large JavaScript web applications is the build process. The majority of non-trivial apps are likely to consist of more than one or two scripts and so optimizing, minimizing and concatenating your scripts prior to pushing them to production will require your users to download a reduced number (if not just one) script file.
  1843. Note: If you haven't looked at build processes before and this is your first time hearing about them, you might find [my post and screencast on this topic](http://addyosmani.com/blog/client-side-build-process/) useful.
  1844. With some other structural JavaScript frameworks, my recommendation would normally be to implicitly use YUI Compressor or Google's closure compiler tools, but we have a slightly more elegant method available, when it comes to Backbone if you're using RequireJS. RequireJS has a command line optimization tool called r.js which has a number of capabilities, including:
  1845. * Concatenating specific scripts and minifying them using external tools such as UglifyJS (which is used by default) or Google's Closure Compiler for optimal browser delivery, whilst preserving the ability to dynamically load modules
  1846. * Optimizing CSS and stylesheets by inlining CSS files imported using @import, stripping out comments etc.
  1847. * The ability to run AMD projects in both Node and Rhino (more on this later)
  1848. You'll notice that I mentioned the word 'specific' in the first bullet point. The RequireJS optimizer only concatenates module scripts that have been specified in arrays of string literals passed to top-level (i.e non-local) require and define calls. As clarified by the [optimizer docs](http://requirejs.org/docs/optimization.html) this means that Backbone modules defined like this:
  1849. ```javascript
  1850. define(['jquery','backbone','underscore', 'collections/sample','views/test'],
  1851. function($,Backbone, _, Sample, Test){
  1852. //...
  1853. });
  1854. ```
  1855. will combine fine, however inline dependencies such as:
  1856. ```javascript
  1857. var models = someCondition ? ['models/ab','models/ac'] : ['models/ba','models/bc'];
  1858. ```
  1859. will be ignored. This is by design as it ensures that dynamic dependency/module loading can still take place even after optimization.
  1860. Although the RequireJS optimizer works fine in both Node and Java environments, it's strongly recommended to run it under Node as it executes significantly faster there. In my experience, it's a piece of cake to get setup with either environment, so go for whichever you feel most comfortable with.
  1861. To get started with r.js, grab it from the [RequireJS download page](http://requirejs.org/docs/download.html#rjs) or [through NPM](http://requirejs.org/docs/optimization.html#download). Now, the RequireJS optimizer works absolutely fine for single script and CSS files, but for most cases you'll want to actually optimize an entire Backbone project. You *could* do this completely from the command-line, but a cleaner option is using build profiles.
  1862. Below is an example of a build file taken from the modular jQuery Mobile app referenced later in this book. A **build profile** (commonly named `app.build.js`) informs RequireJS to copy all of the content of `appDir` to a directory defined by `dir` (in this case `../release`). This will apply all of the necessary optimizations inside the release folder. The `baseUrl` is used to resolve the paths for your modules. It should ideally be relative to `appDir`.
  1863. Near the bottom of this sample file, you'll see an array called `modules`. This is where you specify the module names you wish to have optimized. In this case we're optimizing the main application called 'app', which maps to `appDir/app.js`. If we had set the `baseUrl` to 'scripts', it would be mapped to `appDir/scripts/app.js`.
  1864. ```javascript
  1865. ({
  1866. appDir: "./",
  1867. baseUrl: "./",
  1868. dir: "../release",
  1869. paths: {
  1870. 'backbone': 'libs/AMDbackbone-0.5.3',
  1871. 'underscore': 'libs/underscore-1.2.2',
  1872. 'jquery': 'libs/jQuery-1.7.1',
  1873. 'json2': 'libs/json2',
  1874. 'datepicker': 'libs/jQuery.ui.datepicker',
  1875. 'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
  1876. 'jquerymobile': 'libs/jquery.mobile-1.0'
  1877. },
  1878. optimize: "uglify",
  1879. modules: [
  1880. {
  1881. name: "app",
  1882. exclude: [
  1883. // If you prefer not to include certain libs exclude them here
  1884. ]
  1885. }
  1886. ]
  1887. })
  1888. ```
  1889. The way the build system in r.js works is that it traverses app.js (whatever modules you've passed) and resolved dependencies, concatenating them into the final `release`(dir) folder. CSS is treated the same way.
  1890. The build profile is usually placed inside the 'scripts' or 'js' directory of your project. As per the docs, this file can however exist anywhere you wish, but you'll need to edit the contents of your build profile accordingly.
  1891. Finally, to run the build, execute the following command once inside your `appDir` or `appDir/scripts` directory:
  1892. ```javascript
  1893. node ../../r.js -o app.build.js
  1894. ```
  1895. That's it. As long as you have UglifyJS/Closure tools setup correctly, r.js should be able to easily optimize your entire Backbone project in just a few key-strokes. If you would like to learn more about build profiles, James Burke has a [heavily commented sample file](https://github.com/jrburke/r.js/blob/master/build/example.build.js) with all the possible options available.
  1896. ##<a name="practicalrequirejs">Practical: Building a modular Backbone app with AMD & RequireJS</a>
  1897. In this chapter, we'll look at our first practical Backbone & RequireJS project - how to build a modular Todo application. The application will allow us to add new todos, edit new todos and clear todo items that have been marked as completed. For a more advanced practical, see the section on mobile Backbone development.
  1898. The complete code for the application can can be found in the `practicals/modular-todo-app` folder of this repo (thanks to Thomas Davis and J&eacute;r&ocirc;me Gravel-Niquet). Alternatively grab a copy of my side-project [TodoMVC](https://github.com/addyosmani/todomvc) which contains the sources to both AMD and non-AMD versions.
  1899. **Note:** Thomas may be covering a practical on this exercise in more detail on [backbonetutorials.com](http://backbonetutorials.com) at some point soon, but for this section I'll be covering what I consider the core concepts.
  1900. ###Overview
  1901. Writing a 'modular' Backbone application can be a straight-forward process. There are however, some key conceptual differences to be aware of if opting to use AMD as your module format of choice:
  1902. * As AMD isn't a standard native to JavaScript or the browser, it's necessary to use a script loader (such as RequireJS or curl.js) in order to support defining components and modules using this module format. As we've already reviewed, there are a number of advantages to using the AMD as well as RequireJS to assist here.
  1903. * Models, views, controllers and routers need to be encapsulated *using* the AMD-format. This allows each component of our Backbone application to cleanly manage dependencies (e.g collections required by a view) in the same way that AMD allows non-Backbone modules to.
  1904. * Non-Backbone components/modules (such as utilities or application helpers) can also be encapsulated using AMD. I encourage you to try developing these modules in such a way that they can both be used and tested independent of your Backbone code as this will increase their ability to be re-used elsewhere.
  1905. Now that we've reviewed the basics, let's take a look at developing our application. For reference, the structure of our app is as follows:
  1906. ```
  1907. index.html
  1908. ...js/
  1909. main.js
  1910. .../models
  1911. todo.js
  1912. .../views
  1913. app.js
  1914. todos.js
  1915. .../collections
  1916. todos.js
  1917. .../templates
  1918. stats.html
  1919. todos.html
  1920. ../libs
  1921. .../backbone
  1922. .../jquery
  1923. .../underscore
  1924. .../require
  1925. require.js
  1926. text.js
  1927. ...css/
  1928. ```
  1929. ###Markup
  1930. The markup for the application is relatively simple and consists of three primary parts: an input section for entering new todo items (`create-todo`), a list section to display existing items (which can also be edited in-place) (`todo-list`) and finally a section summarizing how many items are left to be completed (`todo-stats`).
  1931. ```
  1932. <div id="todoapp">
  1933. <div class="content">
  1934. <div id="create-todo">
  1935. <input id="new-todo" placeholder="What needs to be done?" type="text" />
  1936. <span class="ui-tooltip-top">Press Enter to save this task</span>
  1937. </div>
  1938. <div id="todos">
  1939. <ul id="todo-list"></ul>
  1940. </div>
  1941. <div id="todo-stats"></div>
  1942. </div>
  1943. </div>
  1944. ```
  1945. The rest of the tutorial will now focus on the JavaScript side of the practical.
  1946. ###Configuration options
  1947. If you've read the earlier chapter on AMD, you may have noticed that explicitly needing to define each dependency a Backbone module (view, collection or other module) may require with it can get a little tedious. This can however be improved.
  1948. In order to simplify referencing common paths the modules in our application may use, we use a RequireJS [configuration object](http://requirejs.org/docs/api.html#config), which is typically defined as a top-level script file. Configuration objects have a number of useful capabilities, the most useful being mode name-mapping. Name-maps are basically a key:value pair, where the key defines the alias you wish to use for a path and the value represents the true location of the path.
  1949. In the code-sample below, you can see some typical examples of common name-maps which include: `backbone`, `underscore`, `jquery` and depending on your choice, the RequireJS `text` plugin, which assists with loading text assets like templates.
  1950. **main.js**
  1951. ```javascript
  1952. require.config({
  1953. baseUrl:'../',
  1954. paths: {
  1955. jquery: 'libs/jquery/jquery-min',
  1956. underscore: 'libs/underscore/underscore-min',
  1957. backbone: 'libs/backbone/backbone-optamd3-min',
  1958. text: 'libs/require/text'
  1959. }
  1960. });
  1961. require(['views/app'], function(AppView){
  1962. var app_view = new AppView;
  1963. });
  1964. ```
  1965. The `require()` at the end of our main.js file is simply there so we can load and instantiation the primary view for our application (`views/app.js`). You'll commonly see both this and the configuration object included the most top-level script file for a project.
  1966. In addition to offering name-mapping, the configuration object can be used to define additional properties such as `waitSeconds` - the number of seconds to wait before script loading times out and `locale`, should you wish to load up i18n bundles for custom languages. The `baseUrl` is simply the path to use for module lookups.
  1967. For more information on configuration objects, please feel free to check out the excellent guide to them in the [RequireJS docs](http://requirejs.org/docs/api.html#config).
  1968. ###Modularizing our models, views and collections
  1969. Before we dive into AMD-wrapped versions of our Backbone components, let's review a sample of a non-AMD view. The following view listens for changes to its model (a Todo item) and re-renders if a user edits the value of the item.
  1970. ```javascript
  1971. var TodoView = Backbone.View.extend({
  1972. //... is a list tag.
  1973. tagName: "li",
  1974. // Cache the template function for a single item.
  1975. template: _.template($('#item-template').html()),
  1976. // The DOM events specific to an item.
  1977. events: {
  1978. "click .check" : "toggleDone",
  1979. "dblclick div.todo-content" : "edit",
  1980. "click span.todo-destroy" : "clear",
  1981. "keypress .todo-input" : "updateOnEnter"
  1982. },
  1983. // The TodoView listens for changes to its model, re-rendering. Since there's
  1984. // a one-to-one correspondence between a **Todo** and a **TodoView** in this
  1985. // app, we set a direct reference on the model for convenience.
  1986. initialize: function() {
  1987. this.model.on('change', this.render, this);
  1988. this.model.view = this;
  1989. },
  1990. ...
  1991. ```
  1992. Note how for templating the common practice of referencing a script by an ID (or other selector) and obtaining its value is used. This of course requires that the template being accessed is implicitly defined in our markup. The following is the 'embedded' version of our template being referenced above:
  1993. ```
  1994. <script type="text/template" id="item-template">
  1995. <div class="todo <%= done ? 'done' : '' %>">
  1996. <div class="display">
  1997. <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
  1998. <div class="todo-content"></div>
  1999. <span class="todo-destroy"></span>
  2000. </div>
  2001. <div class="edit">
  2002. <input class="todo-input" type="text" value="" />
  2003. </div>
  2004. </div>
  2005. </script>
  2006. ```
  2007. Whilst there is nothing wrong with the template itself, once we begin to develop larger applications requiring multiple templates, including them all in our markup on page-load can quickly become both unmanageable and come with performance costs. We'll look at solving this problem in a minute.
  2008. Let's now take a look at the AMD-version of our view. As discussed earlier, the 'module' is wrapped using AMD's `define()` which allows us to specify the dependencies our view requires. Using the mapped paths to 'jquery' etc. simplifies referencing common dependencies and instances of dependencies are themselves mapped to local variables that we can access (e.g 'jquery' is mapped to `$`).
  2009. **views/todos.js**
  2010. ```javascript
  2011. define([
  2012. 'jquery',
  2013. 'underscore',
  2014. 'backbone',
  2015. 'text!templates/todos.html'
  2016. ], function($, _, Backbone, todosTemplate){
  2017. var TodoView = Backbone.View.extend({
  2018. //... is a list tag.
  2019. tagName: "li",
  2020. // Cache the template function for a single item.
  2021. template: _.template(todosTemplate),
  2022. // The DOM events specific to an item.
  2023. events: {
  2024. "click .check" : "toggleDone",
  2025. "dblclick div.todo-content" : "edit",
  2026. "click span.todo-destroy" : "clear",
  2027. "keypress .todo-input" : "updateOnEnter"
  2028. },
  2029. // The TodoView listens for changes to its model, re-rendering. Since there's
  2030. // a one-to-one correspondence between a **Todo** and a **TodoView** in this
  2031. // app, we set a direct reference on the model for convenience.
  2032. initialize: function() {
  2033. this.model.on('change', this.render, this);
  2034. this.model.view = this;
  2035. },
  2036. // Re-render the contents of the todo item.
  2037. render: function() {
  2038. this.$el.html(this.template(this.model.toJSON()));
  2039. this.setContent();
  2040. return this;
  2041. },
  2042. // Use `jQuery.text` to set the contents of the todo item.
  2043. setContent: function() {
  2044. var content = this.model.get('content');
  2045. this.$('.todo-content').text(content);
  2046. this.input = this.$('.todo-input');
  2047. this.input.on('blur', this.close);
  2048. this.input.val(content);
  2049. },
  2050. ...
  2051. ```
  2052. From a maintenance perspective, there's nothing logically different in this version of our view, except for how we approach templating.
  2053. Using the RequireJS text plugin (the dependency marked `text`), we can actually store all of the contents for the template we looked at earlier in an external file (todos.html).
  2054. **templates/todos.html**
  2055. ```html
  2056. <div class="todo <%= done ? 'done' : '' %>">
  2057. <div class="display">
  2058. <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
  2059. <div class="todo-content"></div>
  2060. <span class="todo-destroy"></span>
  2061. </div>
  2062. <div class="edit">
  2063. <input class="todo-input" type="text" value="" />
  2064. </div>
  2065. </div>
  2066. ```
  2067. There's no longer a need to be concerned with IDs for the template as we can map it's contents to a local variable (in this case `todosTemplate`). We then simply pass this to the Underscore.js templating function `_.template()` the same way we normally would have the value of our template script.
  2068. Next, let's look at how to define models as dependencies which can be pulled into collections. Here's an AMD-compatible model module, which has two default values: a `content` attribute for the content of a Todo item and a boolean `done` state, allowing us to trigger whether the item has been completed or not.
  2069. **models/todo.js**
  2070. ```javascript
  2071. define(['underscore', 'backbone'], function(_, Backbone) {
  2072. var TodoModel = Backbone.Model.extend({
  2073. // Default attributes for the todo.
  2074. defaults: {
  2075. // Ensure that each todo created has `content`.
  2076. content: "empty todo...",
  2077. done: false
  2078. },
  2079. initialize: function() {
  2080. },
  2081. // Toggle the `done` state of this todo item.
  2082. toggle: function() {
  2083. this.save({done: !this.get("done")});
  2084. },
  2085. // Remove this Todo from *localStorage* and delete its view.
  2086. clear: function() {
  2087. this.destroy();
  2088. this.view.remove();
  2089. }
  2090. });
  2091. return TodoModel;
  2092. });
  2093. ```
  2094. As per other types of dependencies, we can easily map our model module to a local variable (in this case `Todo`) so it can be referenced as the model to use for our `TodosCollection`. This collection also supports a simple `done()` filter for narrowing down Todo items that have been completed and a `remaining()` filter for those that are still outstanding.
  2095. **collections/todos.js**
  2096. ```javascript
  2097. define([
  2098. 'underscore',
  2099. 'backbone',
  2100. 'libs/backbone/localstorage',
  2101. 'models/todo'
  2102. ], function(_, Backbone, Store, Todo){
  2103. var TodosCollection = Backbone.Collection.extend({
  2104. // Reference to this collection's model.
  2105. model: Todo,
  2106. // Save all of the todo items under the `"todos"` namespace.
  2107. localStorage: new Store("todos"),
  2108. // Filter down the list of all todo items that are finished.
  2109. done: function() {
  2110. return this.filter(function(todo){ return todo.get('done'); });
  2111. },
  2112. // Filter down the list to only todo items that are still not finished.
  2113. remaining: function() {
  2114. return this.without.apply(this, this.done());
  2115. },
  2116. ...
  2117. ```
  2118. In addition to allowing users to add new Todo items from views (which we then insert as models in a collection), we ideally also want to be able to display how many items have been completed and how many are remaining. We've already defined filters that can provide us this information in the above collection, so let's use them in our main application view.
  2119. **views/app.js**
  2120. ```javascript
  2121. define([
  2122. 'jquery',
  2123. 'underscore',
  2124. 'backbone',
  2125. 'collections/todos',
  2126. 'views/todos',
  2127. 'text!templates/stats.html'
  2128. ], function($, _, Backbone, Todos, TodoView, statsTemplate){
  2129. var AppView = Backbone.View.extend({
  2130. // Instead of generating a new element, bind to the existing skeleton of
  2131. // the App already present in the HTML.
  2132. el: $("#todoapp"),
  2133. // Our template for the line of statistics at the bottom of the app.
  2134. statsTemplate: _.template(statsTemplate),
  2135. // ...events, initialize() etc. can be seen in the complete file
  2136. // Re-rendering the App just means refreshing the statistics -- the rest
  2137. // of the app doesn't change.
  2138. render: function() {
  2139. var done = Todos.done().length;
  2140. this.$('#todo-stats').html(this.statsTemplate({
  2141. total: Todos.length,
  2142. done: Todos.done().length,
  2143. remaining: Todos.remaining().length
  2144. }));
  2145. },
  2146. ...
  2147. ```
  2148. Above, we map the second template for this project, `templates/stats.html` to `statsTemplate` which is used for rendering the overall `done` and `remaining` states. This works by simply passing our template the length of our overall Todos collection (`Todos.length` - the number of Todo items created so far) and similarly the length (counts) for items that have been completed (`Todos.done().length`) or are remaining (`Todos.remaining().length`).
  2149. The contents of our `statsTemplate` can be seen below. It's nothing too complicated, but does use ternary conditions to evaluate whether we should state there's "1 item" or "2 item<i>s</i>" in a particular state.
  2150. ```
  2151. <% if (total) { %>
  2152. <span class="todo-count">
  2153. <span class="number"><%= remaining %></span>
  2154. <span class="word"><%= remaining == 1 ? 'item' : 'items' %></span> left.
  2155. </span>
  2156. <% } %>
  2157. <% if (done) { %>
  2158. <span class="todo-clear">
  2159. <a href="#">
  2160. Clear <span class="number-done"><%= done %></span>
  2161. completed <span class="word-done"><%= done == 1 ? 'item' : 'items' %></span>
  2162. </a>
  2163. </span>
  2164. <% } %>
  2165. ```
  2166. The rest of the source for the Todo app mainly consists of code for handling user and application events, but that rounds up most of the core concepts for this practical.
  2167. To see how everything ties together, feel free to grab the source by cloning this repo or browse it [online](https://github.com/addyosmani/backbone-fundamentals/tree/master/practicals/modular-todo-app) to learn more. I hope you find it helpful!.
  2168. **Note:** While this first practical doesn't use a build profile as outlined in the chapter on using the RequireJS optimizer, we will be using one in the section on building mobile Backbone applications.
  2169. ##<a name="decouplingbackbone">Decoupling Backbone with the Mediator and Facade patterns</a>
  2170. In this section we'll discuss applying some of the concepts I cover in my article on [Large-scale JavaScript Application development](http://addyosmani.com/largescalejavascript) to Backbone.
  2171. ### Summary
  2172. At a high-level, one architecture that works for such applications is something which is:
  2173. * **Highly decoupled**: encouraging modules to only publish and subscribe to events of interest rather than directly communicating with each other. This helps us to build applications who's units of code aren't highly tied (coupled) together and can thus be reused more easily.
  2174. * **Supports module-level security**: whereby modules are only able to execute behavior they've been permitted to. Application security is an area which is often overlooked in JavaScript applications, but can be quite easily implemented in a flexible manner.
  2175. * **Supports failover**: allowing an application continuing to function even if particular modules fail. The typical example I give of this is the GMail chat widget. Imagine being able to build applications in a way that if one widget on the page fails (e.g chat), the rest of your application (mail) can continue to function without being affected.
  2176. This is an architecture which has been implemented by a number of different companies in the past, including Yahoo! (for their modularized homepage - which Nicholas Zakas has [spoken](http://www.youtube.com/watch?v=vXjVFPosQHw) about) and AOL for some of our upcoming projects.
  2177. The three design patterns that make this architecture possible are the:
  2178. * **Module pattern**: used for encapsulating unique blocks of code, where functions and variables can be kept either public or private. ('private' in the simulation of privacy sense, as of course don't have true privacy in JavaScript)
  2179. * **Mediator pattern**: used when the communication between modules may be complex, but is still well defined. If it appears a system may have too many relationships between modules in your code, it may be time to have a central point of control, which is where the pattern fits in.
  2180. * **Facade pattern**: used for providing a convenient higher-level interface to a larger body of code, hiding its true underlying complexity
  2181. Their specific roles in this architecture can be found below.
  2182. * **Modules**: There are almost two concepts of what defines a module. As AMD is being used as a module wrapper, technically each model, view and collection can be considered a module. We then have the concept of modules being distinct blocks of code outside of just MVC/MV*. For the latter, these types of 'modules' are primarily concerned with broadcasting and subscribing to events of interest rather than directly communicating with each other.They are made possible through the Mediator pattern.
  2183. * **Mediator**: The mediator has a varying role depending on just how you wish to implement it. In my article, I mention using it as a module manager with the ability to start and stop modules at will, however when it comes to Backbone, I feel that simplifying it down to the role of a central 'controller' that provides pub/sub capabilities should suffice. One can of course go all out in terms of building a module system that supports module starting, stopping, pausing etc, however the scope of this is outside of this chapter.
  2184. * **Facade**: This acts as a secure middle-layer that both abstracts an application core (Mediator) and relays messages from the modules back to the Mediator so they don't touch it directly. The Facade also performs the duty of application security guard; it checks event notifications from modules against a configuration (permissions.js, which we will look at later) to ensure requests from modules are only processed if they are permitted to execute the behavior passed.
  2185. For ease of reference, I sometimes refer to these three patterns grouped together as Aura (a word that means subtle, luminous light).
  2186. ### Practical
  2187. For the practical section of this chapter, we'll be extending the well-known Backbone Todo application using the three patterns mentioned above. The complete code for this section can be found here: https://github.com/addyosmani/backbone-aura and should ideally be run on at minimum, a local HTTP server.
  2188. The application is broken down into AMD modules that cover everything from Backbone models through to application-level modules. The views publish events of interest to the rest of the application and modules can then subscribe to these event notifications.
  2189. All subscriptions from modules go through a facade (or sandbox). What this does is check against the subscriber name and the 'channel/notification' it's attempting to subscribe to. If a channel *doesn't* have permissions to be subscribed to (something established through permissions.js), the subscription isn't permitted.
  2190. **Mediator**
  2191. Found in `aura/mediator.js`
  2192. Below is a very simple AMD-wrapped implementation of the mediator pattern, based on prior work by Ryan Florence. It accepts as it's input an object, to which it attaches `publish()` and `subscribe()` methods. In a larger application, the mediator can contain additional utilities, such as handlers for initializing, starting and stopping modules, but for demonstration purposes, these two methods should work fine for our needs.
  2193. ```javascript
  2194. define([], function(obj){
  2195. var channels = {};
  2196. if (!obj) obj = {};
  2197. obj.subscribe = function (channel, subscription) {
  2198. if (!channels[channel]) channels[channel] = [];
  2199. channels[channel].push(subscription);
  2200. };
  2201. obj.publish = function (channel) {
  2202. if (!channels[channel]) return;
  2203. var args = [].slice.call(arguments, 1);
  2204. for (var i = 0, l = channels[channel].length; i < l; i++) {
  2205. channels[channel][i].apply(this, args);
  2206. }
  2207. };
  2208. return obj;
  2209. });
  2210. ```
  2211. **Facade**
  2212. Found in `aura/facade.js`
  2213. Next, we have an implementation of the facade pattern. Now the classical facade pattern applied to JavaScript would probably look a little like this:
  2214. ```javascript
  2215. var module = (function() {
  2216. var _private = {
  2217. i:5,
  2218. get : function() {
  2219. console.log('current value:' + this.i);
  2220. },
  2221. set : function( val ) {
  2222. this.i = val;
  2223. },
  2224. run : function() {
  2225. console.log('running');
  2226. },
  2227. jump: function(){
  2228. console.log('jumping');
  2229. }
  2230. };
  2231. return {
  2232. facade : function( args ) {
  2233. _private.set(args.val);
  2234. _private.get();
  2235. if ( args.run ) {
  2236. _private.run();
  2237. }
  2238. }
  2239. }
  2240. }());
  2241. module.facade({run: true, val:10});
  2242. //outputs current value: 10, running
  2243. ```
  2244. It's effectively a variation of the module pattern, where instead of simply returning an interface of supported methods, your API can completely hide the true implementation powering it, returning something simpler. This allows the logic being performed in the background to be as complex as necessary, whilst all the end-user experiences is a simplified API they pass options to (note how in our case, a single method abstraction is exposed). This is a beautiful way of providing APIs that can be easily consumed.
  2245. That said, to keep things simple, our implementation of an AMD-compatible facade will act a little more like a proxy. Modules will communicate directly through the facade to access the mediator's `publish()` and `subscribe()` methods, however, they won't as such touch the mediator directly.This enables the facade to provide application-level validation of any subscriptions and publications made.
  2246. It also allows us to implement a simple, but flexible, permissions checker (as seen below) which will validate subscriptions made against a permissions configuration to see whether it's permitted or not.
  2247. ```javascript
  2248. define([ "../aura/mediator" , "../aura/permissions" ], function (mediator, permissions) {
  2249. var facade = facade || {};
  2250. facade.subscribe = function(subscriber, channel, callback){
  2251. // Note: Handling permissions/security is optional here
  2252. // The permissions check can be removed
  2253. // to just use the mediator directly.
  2254. if(permissions.validate(subscriber, channel)){
  2255. mediator.subscribe( channel, callback );
  2256. }
  2257. }
  2258. facade.publish = function(channel){
  2259. mediator.publish( channel );
  2260. }
  2261. return facade;
  2262. });
  2263. ```
  2264. **Permissions**
  2265. Found in `aura/permissions.js`
  2266. In our simple permissions configuration, we support checking against subscription requests to establish whether they are allowed to clear. This enforces a flexible security layer for the application.
  2267. To visually see how this works, consider changing say, permissions -> renderDone -> todoCounter to be false. This will completely disable the application from from rendering or displaying the counts component for Todo items left (because they aren't allowed to subscribe to that event notification). The rest of the Todo app can still however be used without issue.
  2268. It's a very dumbed down example of the potential for application security, but imagine how powerful this might be in a large app with a significant number of visual widgets.
  2269. ```javascript
  2270. define([], function () {
  2271. // Permissions
  2272. // A permissions structure can support checking
  2273. // against subscriptions prior to allowing them
  2274. // to clear. This enforces a flexible security
  2275. // layer for your application.
  2276. var permissions = {
  2277. newContentAvailable: {
  2278. contentUpdater:true
  2279. },
  2280. endContentEditing:{
  2281. todoSaver:true
  2282. },
  2283. beginContentEditing:{
  2284. editFocus:true
  2285. },
  2286. addingNewTodo:{
  2287. todoTooltip:true
  2288. },
  2289. clearContent:{
  2290. garbageCollector:true
  2291. },
  2292. renderDone:{
  2293. todoCounter:true //switch to false to see what happens :)
  2294. },
  2295. destroyContent:{
  2296. todoRemover:true
  2297. },
  2298. createWhenEntered:{
  2299. keyboardManager:true
  2300. }
  2301. };
  2302. permissions.validate = function(subscriber, channel){
  2303. var test = permissions[channel][subscriber];
  2304. return test===undefined? false: test;
  2305. };
  2306. return permissions;
  2307. });
  2308. ```
  2309. **Subscribers**
  2310. Found in `subscribers.js`
  2311. Subscriber 'modules' communicate through the facade back to the mediator and perform actions when a notification event of a particular name is published.
  2312. For example, when a user enters in a new piece of text for a Todo item and hits 'enter' the application publishes a notification saying two things: a) a new Todo item is available and b) the text content of the new item is X. It's then left up to the rest of the application to do with this information whatever it wishes.
  2313. In order to update your Backbone application to primarily use pub/sub, a lot of the work you may end up doing will be moving logic coupled inside of specific views to modules outside of it which are reactionary.
  2314. Take the `todoSaver` for example - it's responsibility is saving new Todo items to models once the a `notificationName` called 'newContentAvailable' has fired. If you take a look at the permissions structure in the last code sample, you'll notice that 'newContentAvailable' is present there. If I wanted to prevent subscribers from being able to subscribe to this notification, I simply set it to a boolean value of `false`.
  2315. Again, this is a massive oversimplification of how advanced your permissions structures could get, but it's certainly one way of controlling what parts of your application can or can't be accessed by specific modules at any time.
  2316. ```javascript
  2317. define(["jquery", "underscore", "aura/facade"],
  2318. function ($, _, facade) {
  2319. // Subscription 'modules' for our views. These take the
  2320. // the form facade.subscribe( subscriberName, notificationName , callBack )
  2321. // Update view with latest todo content
  2322. // Subscribes to: newContentAvailable
  2323. facade.subscribe('contentUpdater', 'newContentAvailable', function (context) {
  2324. var content = context.model.get('content');
  2325. context.$('.todo-content').text(content);
  2326. context.input = context.$('.todo-input');
  2327. context.input.bind('blur', context.close);
  2328. context.input.val(content);
  2329. });
  2330. // Save models when a user has finishes editing
  2331. // Subscribes to: endContentEditing
  2332. facade.subscribe('todoSaver','endContentEditing', function (context) {
  2333. try {
  2334. context.model.save({
  2335. content: context.input.val()
  2336. });
  2337. context.$el.removeClass("editing");
  2338. } catch (e) {
  2339. //console.log(e);
  2340. }
  2341. });
  2342. // Delete a todo when the user no longer needs it
  2343. // Subscribes to: destroyContent
  2344. facade.subscribe('todoRemover','destroyContent', function (context) {
  2345. try {
  2346. context.model.clear();
  2347. } catch (e) {
  2348. //console.log(e);
  2349. }
  2350. });
  2351. // When a user is adding a new entry, display a tooltip
  2352. // Subscribes to: addingNewTodo
  2353. facade.subscribe('todoTooltip','addingNewTodo', function (context, todo) {
  2354. var tooltip = context.$(".ui-tooltip-top");
  2355. var val = context.input.val();
  2356. tooltip.fadeOut();
  2357. if (context.tooltipTimeout) clearTimeout(context.tooltipTimeout);
  2358. if (val == '' || val == context.input.attr('placeholder')) return;
  2359. var show = function () {
  2360. tooltip.show().fadeIn();
  2361. };
  2362. context.tooltipTimeout = _.delay(show, 1000);
  2363. });
  2364. // Update editing UI on switching mode to editing content
  2365. // Subscribes to: beginContentEditing
  2366. facade.subscribe('editFocus','beginContentEditing', function (context) {
  2367. context.$el.addClass("editing");
  2368. context.input.focus();
  2369. });
  2370. // Create a new todo entry
  2371. // Subscribes to: createWhenEntered
  2372. facade.subscribe('keyboardManager','createWhenEntered', function (context, e, todos) {
  2373. if (e.keyCode != 13) return;
  2374. todos.create(context.newAttributes());
  2375. context.input.val('');
  2376. });
  2377. // A Todo and remaining entry counter
  2378. // Subscribes to: renderDone
  2379. facade.subscribe('todoCounter','renderDone', function (context, Todos) {
  2380. var done = Todos.done().length;
  2381. context.$('#todo-stats').html(context.statsTemplate({
  2382. total: Todos.length,
  2383. done: Todos.done().length,
  2384. remaining: Todos.remaining().length
  2385. }));
  2386. });
  2387. // Clear all completed todos when clearContent is dispatched
  2388. // Subscribes to: clearContent
  2389. facade.subscribe('garbageCollector','clearContent', function (Todos) {
  2390. _.each(Todos.done(), function (todo) {
  2391. todo.clear();
  2392. });
  2393. });
  2394. });
  2395. ```
  2396. That's it for this section. If you've been intrigued by some of the concepts covered, I encourage you to consider taking a look at my [slides](http://addyosmani.com/blog/large-scale-javascript-application-architecture/) on Large-scale JS from the jQuery Summit or my longer post on the topic [here](http://addyosmani.com/largescalejavascript) for more information.
  2397. ##<a name="pagination">Paginating Backbone.js Requests & Collections</a>
  2398. Pagination is a ubiquitous problem we often find ourselves needing to solve on the web. Perhaps most predominantly when working with back-end APIs and JavaScript-heavy clients which consume them.
  2399. On this topic, we're going to go through a set of **pagination components ** I wrote for Backbone.js, which should hopefully come in useful if you're working on applications which need to tackle this problem. They're part of an extension called [Backbone.Paginator][1].
  2400. When working with a structural framework like Backbone.js, the three types of pagination we are most likely to run into are:
  2401. **Requests to a service layer (API) **- e.g query for results containing the term 'Brendan' - if 5,000 results are available only display 20 results per page (leaving us with 250 possible result pages that can be navigated to).
  2402. This problem actually has quite a great deal more to it, such as maintaining persistence of other URL parameters (e.g sort, query, order) which can change based on a user's search configuration in a UI. One also had to think of a clean way of hooking views up to this pagination so you can easily navigate between pages (e.g First, Last, Next, Previous, 1,2,3), manage the number of results displayed per page and so on.
  2403. **Further client-side pagination of data returned -** e.g we've been returned a JSON esponse containing 100 results. Rather than displaying all 100 to the user, we only display 20 of these results within a navigatable UI in the browser.
  2404. Similar to the request problem, client-pagination has its own challenges like navigation once again (Next, Previous, 1,2,3), sorting, order, switching the number of results to display per page and so on.
  2405. **Infinite results** - with services such as Facebook, the concept of numeric pagination is instead replaced with a 'Load More' or 'View More' button. Triggering this normally fetches the next 'page' of N results but rather than replacing the previous set of results loaded entirely, we simply append to them instead.
  2406. A request pager which simply appends results in a view rather than replacing on each new fetch is effectively an 'infinite' pager.
  2407. **Let's now take a look at exactly what we're getting out of the box:**
  2408. *[Backbone.Paginator][2] is a set of opinionated components for paginating collections of data using Backbone.js. It aims to provide both solutions for assisting with pagination of requests to a server (e.g an API) as well as pagination of single-loads of data, where we may wish to further paginate a collection of N results into M pages within a view.*
  2409. ## Paginator's pieces
  2410. Backbone.Paginator supports two main pagination components:
  2411. * **Backbone.Paginator.requestPager**: For pagination of requests between a client and a server-side API
  2412. * **Backbone.Paginator.clientPager**: For pagination of data returned from a server which you would like to further paginate within the UI (e.g 60 results are returned, paginate into 3 pages of 20)
  2413. ## Downloads And Source Code
  2414. You can either download the raw source code for the project, fork the repository or use one of these links:
  2415. * Production: [production](https://raw.github.com/addyosmani/backbone.baginator/master/dist/backbone.paginator.min.js)
  2416. * Development: [development version](https://raw.github.com/addyosmani/backbone.baginator/master/dist/backbone.paginator.js)
  2417. * Examples + Source : [zipball](https://github.com/addyosmani/backbone.paginator/zipball/v0.153)
  2418. * [Repository]()http://github.com/addyosmani/backbone.paginator)
  2419. ## Live Examples
  2420. Live previews of both pagination components using the Netflix API can be found below. Download the tarball or fork the repository to experiment with these examples further.
  2421. Demo 1: [Backbone.Paginator.requestPager()][3]
  2422. <img alt="" class="aligncenter size-large wp-image-4578" height="451" src="img/requestPager.png" style="margin-left:-17px;" width="600" />
  2423. Demo 2: [Backbone.Paginator.clientPager()][4]
  2424. <img alt="" class="aligncenter size-full wp-image-4579" height="462" src="img/clientPager.png" width="600" />
  2425. Demo 3: [Infinite Pagination (Backbone.Paginator.requestPager())][5]
  2426. <img alt="" class="aligncenter size-large wp-image-4580" height="451" src="img/infinitepager.png" width="600" />
  2427. ## Paginator.requestPager
  2428. In this section we're going to walkthrough actually using the requestPager.
  2429. #### 1. Create a new Paginated collection
  2430. First, we define a new Paginated collection using `Backbone.Paginator.requestPager()` as follows:
  2431. <pre class="javascript" name="code">var PaginatedCollection = Backbone.Paginator.requestPager.extend({
  2432. </pre>
  2433. #### 2: Set the model and base URL for the collection as normal
  2434. Within our collection, we then (as normal) specify the model to be used with this collection followed by the URL (or base URL) for the service providing our data (e.g the Netflix API).
  2435. ```javascript
  2436. model: model,
  2437. url: 'http://odata.netflix.com/v2/Catalog/Titles?&',
  2438. ```
  2439. #### 3. Map the attributes supported by your API (URL)
  2440. Next, we're going to map the request (URL) parameters supported by your API or backend data service back to attributes that are internally used by Backbone.Paginator.
  2441. For example: the NetFlix API refers to it's parameter for stating how many results to skip ahead by as `$skip` and it's number of items to return per page as `$top` (amongst others). We determine these by looking at a sample URL pointing at the service:
  2442. ```javascript
  2443. http://odata.netflix.com/v2/Catalog/Titles?&callback=callback&$top=30&$skip=30&orderBy=ReleaseYear&$inlinecount=allpages&$format=json&$callback=callback&$filter=substringof%28%27the%27,%20Name%29%20eq%20true&_=1332702202090
  2444. ```
  2445. We then simply map these parameters to the relevant Paginator equivalents shown on the left hand side of the next snippets to get everything working:
  2446. ```javascript
  2447. // @param-name for the query field in the
  2448. // request (e.g query/keywords/search)
  2449. queryAttribute: '$filter',
  2450. // @param-name for number of items to return per request/page
  2451. perPageAttribute: '$top',
  2452. // @param-name for how many results the request should skip ahead to
  2453. skipAttribute: '$skip',
  2454. // @param-name for the direction to sort in
  2455. sortAttribute: '$sort',
  2456. // @param-name for field to sort by
  2457. orderAttribute: '$orderBy',
  2458. // @param-name for the format of the request
  2459. formatAttribute: '$format',
  2460. // @param-name for a custom attribute
  2461. customAttribute1: '$inlinecount',
  2462. // @param-name for another custom attribute
  2463. customAttribute2: '$callback',
  2464. ```
  2465. **Note**: you can define support for new custom attributes in Backbone.Paginator if needed (e.g customAttribute1) for those that may be unique to your service.
  2466. #### 4. Configure the default pagination, query and sort details for the paginator
  2467. Now, let's configure the default values in our collection for these parameters so that as a user navigates through the paginated UI, requests are able to continue querying with the correct field to sort on, the right number of items to return per request etc.
  2468. e.g: If we want to request the:
  2469. * 1st page of results
  2470. * for the search query 'superman'
  2471. * in JSON format
  2472. * sorted by release year
  2473. * in ascending order
  2474. * where only 30 results are returned per request
  2475. This would look as follows:
  2476. ```javascript
  2477. // current page to query from the service
  2478. page: 5,
  2479. // The lowest page index your API allows to be accessed
  2480. firstPage: 0, //some begin with 1
  2481. // how many results to query from the service (i.e how many to return
  2482. // per request)
  2483. perPage: 30,
  2484. // maximum number of pages that can be queried from
  2485. // the server (only here as a default in case your
  2486. // service doesn't return the total pages available)
  2487. totalPages: 10,
  2488. // what field should the results be sorted on?
  2489. sortField: 'ReleaseYear',
  2490. // what direction should the results be sorted in?
  2491. sortDirection: 'asc',
  2492. // what would you like to query (search) from the service?
  2493. // as Netflix reqires additional parameters around the query
  2494. // we simply fill these around our search term
  2495. query: "substringof('" + escape('the') + "',Name)",
  2496. // what format would you like to request results in?
  2497. format: 'json',
  2498. // what other custom parameters for the request do
  2499. // you require
  2500. // for your application?
  2501. customParam1: 'allpages',
  2502. customParam2: 'callback',
  2503. ```
  2504. As the particular API we're using requires `callback` and `allpages` parameters to also be passed, we simply define the values for these as custom parameters which can be mapped back to requestPager as needed.
  2505. #### 5. Finally, configure Collection.parse() and we're done
  2506. The last thing we need to do is configure our collection's `parse()` method. We want to ensure we're returning the correct part of our JSON response containing the data our collection will be populated with, which below is `response.d.results` (for the Netflix API).
  2507. You might also notice that we're setting `this.totalPages` to the total page count returned by the API. This allows us to define the maximum number of (result) pages available for the current/last request so that we can clearly display this in the UI. It also allows us to infuence whether clicking say, a 'next' button should proceed with a request or not.
  2508. ```javascript
  2509. parse: function (response) {
  2510. // Be sure to change this based on how your results
  2511. // are structured (e.g d.results is Netflix specific)
  2512. var tags = response.d.results;
  2513. //Normally this.totalPages would equal response.d.__count
  2514. //but as this particular NetFlix request only returns a
  2515. //total count of items for the search, we divide.
  2516. this.totalPages = Math.floor(response.d.__count / this.perPage);
  2517. return tags;
  2518. }
  2519. });
  2520. });
  2521. ```
  2522. #### Convenience methods:
  2523. For your convenience, the following methods are made available for use in your views to interact with the `requestPager`:
  2524. * **Collection.goTo(n)** - go to a specific page
  2525. * **Collection.requestNextPage()** - go to the next page
  2526. * **Collection.requestPreviousPage()** - go to the previous page
  2527. * **Collection.howManyPer(n)** - set the number of items to display per page
  2528. ## Paginator.clientPager
  2529. The `clientPager` works similar to the `requestPager`, except that our configuration values influence the pagination of data already returned at a UI-level. Whilst not shown (yet) there is also a lot more UI logic that ties in with the `clientPager`. An example of this can be seen in ‘views/clientPagination.js.
  2530. #### 1. Create a new paginated collection with a model and URL
  2531. As with `requestPager`, let's first create a new Paginated `Backbone.Paginator.clientPager` collection, with a model and base URL:
  2532. ```javascript
  2533. var PaginatedCollection = Backbone.Paginator.clientPager.extend({
  2534. model: model,
  2535. url: 'http://odata.netflix.com/v2/Catalog/Titles?&',
  2536. ```
  2537. #### 2. Map the attributes supported by your API (URL)
  2538. We're similarly going to map request parameter names for your API to those supported in the paginator:
  2539. ```javascript
  2540. perPageAttribute: '$top',
  2541. skipAttribute: '$skip',
  2542. orderAttribute: '$orderBy',
  2543. customAttribute1: '$inlinecount',
  2544. queryAttribute: '$filter',
  2545. formatAttribute: '$format',
  2546. customAttribute2: '$callback',
  2547. ```
  2548. #### 3. Configure how to paginate data at a UI-level
  2549. We then get to configuration for the paginated data in the UI. `perPage` specifies how many results to return from the server whilst `displayPerPage` configures how many of the items in returned results to display per 'page' in the UI. e.g If we request 100 results and only display 20 per page, we have 5 sub-pages of results that can be navigated through in the UI.
  2550. ```javascript
  2551. // M: how many results to query from the service
  2552. perPage: 40,
  2553. // N: how many results to display per 'page' within the UI
  2554. // Effectively M/N = the number of pages the data will be split into.
  2555. displayPerPage: 20,
  2556. ```
  2557. #### 4. Configure the rest of the request parameter default values
  2558. We can then configure default values for the rest of our request parameters:
  2559. ```javascript
  2560. // current page to query from the service
  2561. page: 1,
  2562. // a default. This should be overridden in the collection's parse()
  2563. // sort direction
  2564. sortDirection: 'asc',
  2565. // sort field
  2566. sortField: 'ReleaseYear',
  2567. //or year(Instant/AvailableFrom)
  2568. // query
  2569. query: "substringof('" + escape('the') + "',Name)",
  2570. // request format
  2571. format: 'json',
  2572. // custom parameters for the request that may be specific to your
  2573. // application
  2574. customParam1: 'allpages',
  2575. customParam2: 'callback',
  2576. ```
  2577. #### 5. Finally, configure Collection.parse() and we're done
  2578. And finally we have our `parse()` method, which in this case isn't concerned with the total number of result pages available on the server as we have our own total count of pages for the paginated data in the UI.
  2579. ```javascript
  2580. parse: function (response) {
  2581. var tags = response.d.results;
  2582. return tags;
  2583. }
  2584. });
  2585. ```
  2586. #### Convenience methods:
  2587. As mentioned, your views can hook into a number of convenience methods to navigate around UI-paginated data. For `clientPager` these include:
  2588. * **Collection.goTo(n)** - go to a specific page
  2589. * **Collection.previousPage()** - go to the previous page
  2590. * **Collection.nextPage()** - go to the next page
  2591. * **Collection.howManyPer(n)** - set how many items to display per page
  2592. * **Collection.pager(sortBy, sortDirection)** - update sort on the current view
  2593. ## Views/Templates
  2594. Although the collection layer is perhaps the most important part of Backbone.Paginator, it would be of little use without views interacting with it. The project zipball comes with three complete examples of using the components with the Netflix API, but here's a sample view and template from the `requestPager()` example for those interested in learning more:
  2595. First, we have a view for a pagination bar in our UI that allows us to navigate around our paginated collection:
  2596. ```javascript
  2597. (function ( views ) {
  2598. views.PaginatedView = Backbone.View.extend({
  2599. events: {
  2600. 'click a.servernext': 'nextResultPage',
  2601. 'click a.serverprevious': 'previousResultPage',
  2602. 'click a.orderUpdate': 'updateSortBy',
  2603. 'click a.serverlast': 'gotoLast',
  2604. 'click a.page': 'gotoPage',
  2605. 'click a.serverfirst': 'gotoFirst',
  2606. 'click a.serverpage': 'gotoPage',
  2607. 'click .serverhowmany a': 'changeCount'
  2608. },
  2609. tagName: 'aside',
  2610. template: _.template($('#tmpServerPagination').html()),
  2611. initialize: function () {
  2612. this.collection.on('reset', this.render, this);
  2613. this.collection.on('change', this.render, this);
  2614. this.$el.appendTo('#pagination');
  2615. },
  2616. render: function () {
  2617. var html = this.template(this.collection.info());
  2618. this.$el.html(html);
  2619. },
  2620. updateSortBy: function (e) {
  2621. e.preventDefault();
  2622. var currentSort = $('#sortByField').val();
  2623. this.collection.updateOrder(currentSort);
  2624. },
  2625. nextResultPage: function (e) {
  2626. e.preventDefault();
  2627. this.collection.requestNextPage();
  2628. },
  2629. previousResultPage: function (e) {
  2630. e.preventDefault();
  2631. this.collection.requestPreviousPage();
  2632. },
  2633. gotoFirst: function (e) {
  2634. e.preventDefault();
  2635. this.collection.goTo(this.collection.information.firstPage);
  2636. },
  2637. gotoLast: function (e) {
  2638. e.preventDefault();
  2639. this.collection.goTo(this.collection.information.lastPage);
  2640. },
  2641. gotoPage: function (e) {
  2642. e.preventDefault();
  2643. var page = $(e.target).text();
  2644. this.collection.goTo(page);
  2645. },
  2646. changeCount: function (e) {
  2647. e.preventDefault();
  2648. var per = $(e.target).text();
  2649. this.collection.howManyPer(per);
  2650. }
  2651. });
  2652. })( app.views );
  2653. ```
  2654. which we use with a template like this to generate the necessary pagination links (more are shown in the full example):
  2655. ```html
  2656. <span class="divider">/</span>
  2657. <% if (page > firstPage) { %>
  2658. <a href="#" class="serverprevious">Previous</a>
  2659. <% }else{ %>
  2660. <span>Previous</span>
  2661. <% }%>
  2662. <% if (page < totalPages) { %>
  2663. <a href="#" class="servernext">Next</a>
  2664. <% } %>
  2665. <% if (firstPage != page) { %>
  2666. <a href="#" class="serverfirst">First</a>
  2667. <% } %>
  2668. <% if (lastPage != page) { %>
  2669. <a href="#" class="serverlast">Last</a>
  2670. <% } %>
  2671. <span class="divider">/</span>
  2672. <span class="cell serverhowmany">
  2673. Show
  2674. <a href="#" class="selected">3</a>
  2675. |
  2676. <a href="#" class="">9</a>
  2677. |
  2678. <a href="#" class="">12</a>
  2679. per page
  2680. </span>
  2681. <span class="divider">/</span>
  2682. <span class="cell first records">
  2683. Page: <span class="current"><%= page %></span>
  2684. of
  2685. <span class="total"><%= totalPages %></span>
  2686. shown
  2687. </span>
  2688. <span class="divider">/</span>
  2689. <span class="cell sort">
  2690. <a href="#" class="orderUpdate btn small">Sort by:</a>
  2691. </span>
  2692. <select id="sortByField">
  2693. <option value="cid">Select a field to sort on</option>
  2694. <option value="ReleaseYear">Release year</option>
  2695. <option value="ShortName">Alphabetical</option>
  2696. </select>
  2697. </span>
  2698. ```
  2699. [1]: http://github.com/addyosmani/backbone.paginator
  2700. [2]: http://addyosmani.github.com/backbone.paginator/
  2701. [3]: http://addyosmani.github.com/backbone.paginator/examples/netflix-request-paging/index.html
  2702. [4]: http://addyosmani.github.com/backbone.paginator/examples/netflix-client-paging/index.html
  2703. [5]: http://addyosmani.github.com/backbone.paginator/examples/netflix-infinite-paging/index.html
  2704. [6]: http://github.com/addyosmani/backbone.paginator/issues
  2705. [7]: https://github.com/cowboy/grunt
  2706. ##Backbone & jQuery Mobile
  2707. ###Resolving the routing conflicts
  2708. The first major hurdle developers typically run into when building Backbone applications with jQuery Mobile is that both frameworks have their own opinions about how to handle application navigation.
  2709. Backbone's routers offer an explicit way to define custom navigation routes through `Backbone.Router`, whilst jQuery Mobile encourages the use of URL hash fragments to reference separate 'pages' or views in the same document. jQuery Mobile also supports automatically pulling in external content for links through XHR calls meaning that there can be quite a lot of inter-framework confusion about what a link pointing at '#photo/id' should actually be doing.
  2710. Some of the solutions that have been previously proposed to work-around this problem included manually patching Backbone or jQuery Mobile. I discourage opting for these techniques as it becomes necessary to manually patch your framework builds when new releases get made upstream.
  2711. There's also [jQueryMobile router](https://github.com/azicchetti/jquerymobile-router), which tries to solve this problem differently, however I think my proposed solution is both simpler and allows both frameworks to cohabit quite peacefully without the need to extend either. What we're after is a way to prevent one framework from listening to hash changes so that we can fully rely on the other (e.g. `Backbone.Router`) to handle this for us exclusively.
  2712. Using jQuery Mobile this can be done by setting:
  2713. ```javascript
  2714. $.mobile.hashListeningEnabled = false;
  2715. ```
  2716. prior to initializing any of your other code.
  2717. I discovered this method looking through some jQuery Mobile commits that didn't make their way into the official docs, but am happy to see that they are now covered here http://jquerymobile.com/test/docs/api/globalconfig.html in more detail.
  2718. The next question that arises is, if we're preventing jQuery Mobile from listening to URL hash changes, how can we still get the benefit of being able to navigate to other sections in a document using the built-in transitions and effects supported? Good question. This can now be solve by simply calling `$.mobile.changePage()` as follows:
  2719. ```javascript
  2720. var url = '#about',
  2721. effect = 'slideup',
  2722. reverse = false,
  2723. changeHash = false;
  2724. $.mobile.changePage( url , { transition: effect}, reverse, changeHash );
  2725. ```
  2726. In the above sample, `url` can refer to a URL or a hash identifier to navigate to, `effect` is simply the transition effect to animate the page in with and the final two parameters decide the direction for the transition (`reverse`) and whether or not the hash in the address bar should be updated (`changeHash`). With respect to the latter, I typically set this to false to avoid managing two sources for hash updates, but feel free to set this to true if you're comfortable doing so.
  2727. **Note:** For some parallel work being done to explore how well the jQuery Mobile Router plugin works with Backbone, you may be interested in checking out https://github.com/Filirom1/jquery-mobile-backbone-requirejs.
  2728. ###Practical: A Backbone, RequireJS/AMD app with jQuery Mobile
  2729. **Note:** The code for this practical can be found in `practicals/modular-mobile-app`.
  2730. ###Getting started
  2731. Once you feel comfortable with the [Backbone fundamentals](http://msdn.microsoft.com/en-us/scriptjunkie/hh377172.aspx) and you've put together a rough wireframe of the app you may wish to build, start to think about your application architecture. Ideally, you'll want to logically separate concerns so that it's as easy as possible to maintain the app in the future.
  2732. **Namespacing**
  2733. For this application, I opted for the nested namespacing pattern. Implemented correctly, this enables you to clearly identify if items being referenced in your app are views, other modules and so on. This initial structure is a sane place to also include application defaults (unless you prefer maintaining those in a separate file).
  2734. ```javascript
  2735. window.mobileSearch = window.mobileSearch || {
  2736. views: {
  2737. appview: new AppView
  2738. },
  2739. routers:{
  2740. workspace:new Workspace()
  2741. },
  2742. utils: utils,
  2743. defaults:{
  2744. resultsPerPage: 16,
  2745. safeSearch: 2,
  2746. maxDate:'',
  2747. minDate:'01/01/1970'
  2748. }
  2749. }
  2750. ```
  2751. **Models**
  2752. In the Flickly application, there are at least two unique types of data that need to be modeled - search results and individual photos, both of which contain additional meta-data like photo titles. If you simplify this down, search results are actually groups of photos in their own right, so the application only requires:
  2753. * A single model (a photo or 'result' entry)
  2754. * A result collection (containing a group of result entries) for search results
  2755. * A photo collection (containing one or more result entries) for individual photos or photos with more than one image
  2756. **Views**
  2757. The views we'll need include an application view, a search results view and a photo view. Static views or pages of the single-page application which do not require a dynamic element to them (e.g an 'about' page) can be easily coded up in your document's markup, independent of Backbone.
  2758. **Routers**
  2759. A number of possible routes need to be taken into consideration:
  2760. * Basic search queries `#search/kiwis`
  2761. * Search queries with additional parameters (e.g sort, pagination) `#search/kiwis/srelevance/p7`
  2762. * Queries for specific photos `#photo/93839`
  2763. * A default route (no parameters passed)
  2764. This tutorial will be expanded shortly to fully cover the demo application. In the mean time, please see the practicals folder for the completed application that demonstrates the router resolution discussed earlier between Backbone and jQuery Mobile.
  2765. ###jQuery Mobile: Going beyond mobile application development
  2766. The majority of jQM apps I've seen in production have been developed for the purpose of providing an optimal experience to users on mobile devices. Given that the framework was developed for this purpose, there's nothing fundamentally wrong with this, but many developers forget that jQM is a UI framework not dissimilar to jQuery UI. It's using the widget factory and is capable of being used for a lot more than we give it credit for.
  2767. If you open up Flickly in a desktop browser, you'll get an image search UI that's modeled on Google.com, however, review the components (buttons, text inputs, tabs) on the page for a moment. The desktop UI doesn't look anything like a mobile application yet I'm still using jQM for theming mobile components; the tabs, date-picker, sliders - everything in the desktop UI is re-using what jQM would be providing users on mobile devices. Thanks to some media queries, the desktop UI can make optimal use of whitespace, expanding component blocks out and providing alternative layouts whilst still making use of jQM as a component framework.
  2768. The benefit of this is that I don't need to go pulling in jQuery UI separately to be able to take advantage of these features. Thanks to the recent ThemeRoller my components can look pretty much exactly how I would like them to and users of the app can get a jQM UI for lower-resolutions and a jQM-ish UI for everything else.
  2769. The takeaway here is just to remember that if you're not (already) going through the hassle of conditional script/style loading based on screen-resolution (using matchMedia.js etc), there are simpler approaches that can be taken to cross-device component theming.
  2770. <a name="testing">Unit Testing</a>
  2771. ---
  2772. #<a name="unittestingjasmine">Unit Testing Backbone Applications With Jasmine</a>
  2773. ##Introduction
  2774. One definition of unit testing is the process of taking the smallest piece of testable code in an application, isolating it from the remainder of your codebase and determining if it behaves exactly as expected. In this section, we'll be taking a look at how to unit test Backbone applications using a popular JavaScript testing framework called [Jasmine](http://pivotal.github.com/jasmine/) from Pivotal Labs.
  2775. For an application to be considered 'well'-tested, distinct functionality should ideally have its own separate unit tests where it's tested against the different conditions you expect it to work under. All tests must pass before functionality is considered 'complete'. This allows developers to both modify a unit of code and it's dependencies with a level of confidence about whether these changes have caused any breakage.
  2776. As a basic example of unit testing is where a developer may wish to assert whether passing specific values through to a sum function results in the correct output being returned. For an example more relevant to this book, we may wish to assert whether a user adding a new Todo item to a list correctly adds a Model of a specific type to a Todos Collection.
  2777. When building modern web-applications, it's typically considered best-practice to include automated unit testing as a part of your development process. Whilst we'll be focusing on Jasmine as a solution for this, there are a number of other alternatives worth considering, including QUnit.
  2778. ##Jasmine
  2779. Jasmine describes itself as a behavior-driven development (BDD) framework for testing JavaScript code. Before we jump into how the framework works, it's useful to understand exactly what [BDD](http://en.wikipedia.org/wiki/Behavior_Driven_Development) is.
  2780. BDD is a second-generation testing approach first described by [Dan North](http://dannorth.net/introducing-bdd/) (the authority on BDD) which attempts to test the behavior of software. It's considered second-generation as it came out of merging ideas from Domain driven design (DDD) and lean software development, helping teams to deliver high quality software by answering many of the more confusing questions early on in the agile process. Such questions commonly include those concerning documentation and testing.
  2781. If you were to read a book on BDD, it's likely to also be described as being 'outside-in and pull-based'. The reason for this is that it borrows the idea of of pulling features from Lean manufacturing which effectively ensures that the right software solutions are being written by a) focusing on expected outputs of the system and b) ensuring these outputs are achieved.
  2782. BDD recognizes that there are usually multiple stakeholders in a project and not a single amorphous user of the system. These different groups will be affected by the software being written in differing ways and will have a varying opinion of what quality in the system means to them. It's for this reason that it's important to understand who the software will be bringing value you and exactly what in it will be valuable to them.
  2783. Finally, BDD relies on automation. Once you've defined the quality expected, your team will likely want to check on the functionality of the solution being built regularly and compare it to the results they expect. In order to facilitate this efficiently, the process has to be automated. BDD relies heavily on the automation of specification-testing and Jasmine is a tool which can assist with this.
  2784. BDD helps both developers and non-technical stakeholders:
  2785. * Better understand and represent the models of the problems being solved
  2786. * Explain supported tests cases in a language that non-developers can read
  2787. * Focus on minimizing translation of the technical code being written and the domain language spoken by the business
  2788. What this means is that developers should be able to show Jasmine unit tests to a project stakeholder and (at a high level, thanks to a common vocabulary being used) they'll ideally be able to understand what the code supports.
  2789. Developers often implement BDD in unison with another testing paradigm known as [TDD](http://en.wikipedia.org/wiki/Test-driven_development) (test-driven development). The main idea behind TDD is:
  2790. * Write unit tests which describe the functionality you would like your code to support
  2791. * Watch these tests fail (as the code to support them hasn't yet been written)
  2792. * Write code to make the tests pass
  2793. * Rinse, repeat and refactor
  2794. In this chapter we're going to use both BDD (with TDD) to write unit tests for a Backbone application.
  2795. ***Note:*** I've seen a lot of developers also opt for writing tests to validate behavior of their code after having written it. While this is fine, note that it can come with pitfalls such as only testing for behavior your code currently supports, rather than behavior the problem needs to be supported.
  2796. ##Suites, Specs & Spies
  2797. When using Jasmine, you'll be writing suites and specifications (specs). Suites basically describe scenarios whilst specs describe what can be done in these scenarios.
  2798. Each spec is a JavaScript function, described with a call to ```it()`` using a description string and a function. The description should describe the behaviour the particular unit of code should exhibit and keeping in mind BDD, it should ideally be meaningful. Here's an example of a basic spec:
  2799. ```javascript
  2800. it('should be incrementing in value', function(){
  2801. var counter = 0;
  2802. counter++;
  2803. });
  2804. ```
  2805. On it's own, a spec isn't particularly useful until expectations are set about the behavior of the code. Expectations in specs are defined using the ```expect()``` function and an [expectation matcher](https://github.com/pivotal/jasmine/wiki/Matchers) (e.g toEqual(), toBeTruthy(), toContain()). A revised example using an expectation matcher would look like:
  2806. ```javascript
  2807. it('should be incrementing in value', function(){
  2808. var counter = 0;
  2809. counter++;
  2810. expect(counter).toEqual(1);
  2811. });
  2812. ```
  2813. The above code passes our behavioral expectation as ```counter`` equals 1. Notice how easy this was to read the expectation on the last line (you probably grokked it without any explanation).
  2814. Specs are grouped into suites which we describe using Jasmine's ```describe()``` function, again passing a string as a description and a function. The name/description for your suite is typically that of the component or module you're testing.
  2815. Jasmine will use it as the group name when it reports the results of the specs you've asked it to run. A simple suite containing our sample spec could look like:
  2816. ```javascript
  2817. describe('Stats', function(){
  2818. it('can increment a number', function(){
  2819. ...
  2820. });
  2821. it('can subtract a number', function(){
  2822. ...
  2823. });
  2824. });
  2825. ```
  2826. Suites also share a functional scope and so it's possible to declare variables and functions inside a describe block which are accessible within specs:
  2827. ```javascript
  2828. describe('Stats', function(){
  2829. var counter = 1;
  2830. it('can increment a number', function(){
  2831. // the counter was = 1
  2832. counter = counter + 1;
  2833. expect(counter).toEqual(2);
  2834. });
  2835. it('can subtract a number', function(){
  2836. // the counter was = 2
  2837. counter = counter - 1;
  2838. expect(counter).toEqual(1);
  2839. });
  2840. });
  2841. ```
  2842. ***Note:*** Suites are executed in the order in which they are described, which can be useful to know if you would prefer to see test results for specific parts of your application reported first.
  2843. Jasmine also supports **spies** - a way to mock, spy and fake behavior in our unit tests. Spies replace the function they're spying on, allowing us to simulate behavior we would like to mock (i.e test free of the actual implementation).
  2844. In the below example, we're spying on the ```setComplete``` method of a dummy Todo function to test that arguments can be passed to it as expected.
  2845. ```javascript
  2846. var Todo = function(){
  2847. };
  2848. Todo.prototype.setComplete = function (arg){
  2849. return arg;
  2850. }
  2851. describe('a simple spy', function(){
  2852. it('should spy on an instance method of a Todo', function(){
  2853. var myTodo = new Todo();
  2854. spyOn(myTodo, 'setComplete');
  2855. myTodo.setComplete('foo bar');
  2856. expect(myTodo.setComplete).toHaveBeenCalledWith('foo bar');
  2857. var myTodo2 = new Todo();
  2858. spyOn(myTodo2, 'setComplete');
  2859. expect(myTodo2.setComplete).not.toHaveBeenCalled();
  2860. });
  2861. });
  2862. ```
  2863. What you're more likely to use spies for is testing [asynchronous](http://en.wikipedia.org/wiki/Asynchronous_communication) behavior in your application such as AJAX requests. Jasmine supports:
  2864. * Writing tests which can mock AJAX requests using spies. This allows us to test code which runs before an AJAX request and right after. It's also possible to mock/fake responses the server can return and the benefit of this type of testing is that it's faster as no real calls are being made to a server
  2865. * Asynchronous tests which don't rely on spies
  2866. For the first kind of test, it's possible to both fake an AJAX request and verify that the request was both calling the correct URL and executed a callback where one was provided.
  2867. ```javascript
  2868. it("the callback should be executed on success", function () {
  2869. spyOn($, "ajax").andCallFake(function(options) {
  2870. options.success();
  2871. });
  2872. var callback = jasmine.createSpy();
  2873. getTodo(15, callback);
  2874. expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/todos/15");
  2875. expect(callback).toHaveBeenCalled();
  2876. });
  2877. function getTodo(id, callback) {
  2878. $.ajax({
  2879. type: "GET",
  2880. url: "/todos/" + id,
  2881. dataType: "json",
  2882. success: callback
  2883. });
  2884. }
  2885. ```
  2886. If you feel lost having seen matchers like ```andCallFake()``` and ```toHaveBeenCalled()```, don't worry. All of these are Spy-specific matchers and are documented on the Jasmine [wiki](https://github.com/pivotal/jasmine/wiki/Spies).
  2887. For the second type of test (asynchronous tests), we can take the above further by taking advantage of three other methods Jasmine supports:
  2888. * runs(function) - a block which runs as if it was directly called
  2889. * waits(timeout) - a native timeout before the next block is run
  2890. * waitsFor(function, optional message, optional timeout) - a way to pause specs until some other work has completed. Jasmine waits until the supplied function returns true here before it moves on to the next block.
  2891. ```javascript
  2892. it("should make an actual AJAX request to a server", function () {
  2893. var callback = jasmine.createSpy();
  2894. getTodo(16, callback);
  2895. waitsFor(function() {
  2896. return callback.callCount > 0;
  2897. });
  2898. runs(function() {
  2899. expect(callback).toHaveBeenCalled();
  2900. });
  2901. });
  2902. function getTodo(id, callback) {
  2903. $.ajax({
  2904. type: "GET",
  2905. url: "todos.json",
  2906. dataType: "json",
  2907. success: callback
  2908. });
  2909. }
  2910. ```
  2911. ***Note:*** It's useful to remember that when making real requests to a web server in your unit tests, this has the potential to massively slow down the speed at which tests run (due to many factors including server latency). As this also introduces an external dependency that can (and should) be minimized in your unit testing, it is strongly recommended that you opt for spies to remove the need for a web server to be used here.
  2912. ##beforeEach and afterEach()
  2913. Jasmine also supports specifying code that can be run before each (```beforeEach()```) and after each (```afterEach```) test. This is useful for enforcing consistent conditions (such as resetting variables that may be required by specs). In the following example, ```beforeEach()``` is used to create a new sample Todo model specs can use for testing attributes.
  2914. ```javascript
  2915. beforeEach(function(){
  2916. this.todo = new Backbone.Model({
  2917. text: "Buy some more groceries",
  2918. done: false
  2919. });
  2920. });
  2921. it("should contain a text value if not the default value", function(){
  2922. expect(this.todo.get('text')).toEqual("Buy some more groceries");
  2923. });
  2924. ```
  2925. Each nested ```describe()``` in your tests can have their own ```beforeEach()``` and ```afterEach()``` methods which support including setup and teardown methods relevant to a particular suite. We'll be using ```beforeEach()``` in practice a little later.
  2926. ##Shared scope
  2927. In the previous section you may have noticed that we initially declared a variable ```this.todo``` in our ```beforeEach()``` call and were then able to continue using this in ```afterEach()```. This is thanks to a powerful feature of Jasmine known as shared functional scope. Shared scope allows ```this``` properties to be common to all blocks (including ```runs()```), but not declared variables (i.e ```var```s).
  2928. ##Getting setup
  2929. Now that we've reviewed some fundamentals, let's go through downloading Jasmine and getting everything setup to write tests.
  2930. A standalone release of Jasmine can be [downloaded](http://pivotal.github.com/jasmine/download.html) from the official release page.
  2931. You'll need a file called SpecRunner.html in addition to the release. It can be downloaded from https://github.com/pivotal/jasmine/tree/master/lib/jasmine-core/example or as part of a download of the complete Jasmine [repo](https://github.com/pivotal/jasmine/zipball/master).Alternatively, you can ```git clone``` the main Jasmine repository from https://github.com/pivotal/jasmine.git.
  2932. Let's review [SpecRunner.html](https://github.com/pivotal/jasmine/blob/master/lib/jasmine-core/example/SpecRunner.html):
  2933. It first includes both Jasmine and the necessary CSS required for reporting:
  2934. <link rel="stylesheet" type="text/css" href="lib/jasmine-1.1.0.rc1/jasmine.css"/>
  2935. <script type="text/javascript" src="lib/jasmine-1.1.0.rc1/jasmine.js"></script>
  2936. <script type="text/javascript" src="lib/jasmine-1.1.0.rc1/jasmine-html.js"></script>
  2937. Next, some sample tests are included:
  2938. <script type="text/javascript" src="spec/SpecHelper.js"></script>
  2939. <script type="text/javascript" src="spec/PlayerSpec.js"></script>
  2940. And finally the sources being tested:
  2941. <script type="text/javascript" src="src/Player.js"></script>
  2942. <script type="text/javascript" src="src/Song.js"></script>
  2943. ***Note:*** Below this section of SpecRunner is code responsible for running the actual tests. Given that we won't be covering modifying this code, I'm going to skip reviewing it. I do however encourage you to take a look through [PlayerSpec.js](https://github.com/pivotal/jasmine/blob/master/lib/jasmine-core/example/spec/PlayerSpec.js) and [SpecHelper.js](https://github.com/pivotal/jasmine/blob/master/lib/jasmine-core/example/spec/SpecHelper.js). They're a useful basic example to go through how a minimal set of tests might work.
  2944. ##TDD With Backbone
  2945. When developing applications with Backbone, it can be necessary to test both individual modules of code as well as modules, views, collections and routers. Taking a TDD approach to testing, let's review some specs for testing these Backbone components using the popular Backbone [Todo](https://github.com/addyosmani/todomvc/tree/master/todo-example/backbone) application. For this section we will be using a modified version of Larry Myers Backbone Koans project, which can be found in the `practicals\jasmine-koans` folder.
  2946. ##<a name="testing-jasmine-models">Models</a>
  2947. The complexity of Backbone models can vary greatly depending on what your application is trying to achieve. In the following example, we're going to test default values, attributes, state changes and validation rules.
  2948. First, we begin our suite for model testing using ```describe()```:
  2949. ```javascript
  2950. describe('Tests for Todo', function() {
  2951. ```
  2952. Models should ideally have default values for attributes. This helps ensure that when creating instances without a value set for any specific attribute, a default one (e.g "") is used instead. The idea here is to allow your application to interact with models without any unexpected behavior.
  2953. In the following spec, we create a new Todo without any attributes passed then check to find out what the value of the ```text``` attribute is. As no value has been set, we expect a default value of ```""`` to be returned.
  2954. ```javascript
  2955. it('Can be created with default values for its attributes.', function() {
  2956. var todo = new Todo();
  2957. expect(todo.get('text')).toBe("");
  2958. });
  2959. ```
  2960. If testing this spec before your models have been written, you'll incur a failing test, as expected. What's required for the spec to pass is a default value for the attribute ```text```. We can implement this default value with some other useful defaults (which we'll be using shortly) in our Todo model as follows:
  2961. ```javascript
  2962. window.Todo = Backbone.Model.extend({
  2963. defaults: function() {
  2964. return {
  2965. text: "",
  2966. done: false,
  2967. order: 0
  2968. };
  2969. }
  2970. ```
  2971. Next, we want to test that our model will pass attributes that are set such that retrieving the value of these attributes after initialization will be what we expect. Notice that here, in addition to testing for an expected value for ```text```, we're also testing the other default values are what we expect them to be.
  2972. ```javascript
  2973. it('Will set passed attributes on the model instance when created.', function() {
  2974. var todo = new Todo({ text: 'Get oil change for car.' });
  2975. // what are the values expected here for each of the
  2976. // attributes in our Todo?
  2977. expect(todo.get('text')).toBe("Get oil change for car.");
  2978. expect(todo.get('done')).toBe(false);
  2979. expect(todo.get('order')).toBe(0);
  2980. });
  2981. ```
  2982. Backbone models support a model.change() event which is triggered when the state of a model changes. In the following example, by 'state' I'm referring to the value of a Todo model's attributes. The reason changes of state are important to test are that there may be state-dependent events in your application e.g you may wish to display a confirmation view once a Todo model has been updated.
  2983. ```javascript
  2984. it('Fires a custom event when the state changes.', function() {
  2985. var spy = jasmine.createSpy('-change event callback-');
  2986. var todo = new Todo();
  2987. // how do we monitor changes of state?
  2988. todo.on('change', spy);
  2989. // what would you need to do to force a change of state?
  2990. todo.set({ text: 'Get oil change for car.' });
  2991. expect(spy).toHaveBeenCalled();
  2992. });
  2993. ```
  2994. It's common to include validation logic in your models to ensure both the input passed from users (and other modules) in the application are 'valid'. A Todo app may wish to validate the text input supplied in case it contains rude words. Similarly if we're storing the ```done``` state of a Todo item using booleans, we need to validate that truthy/falsy values are passed and not just any arbitrary string.
  2995. In the following spec, we take advantage of the fact that validations which fail model.validate() trigger an "error" event. This allows us to test if validations are correctly failing when invalid input is supplied.
  2996. We create an errorCallback spy using Jasmine's built in ```createSpy()``` method which allows us to spy on the error event as follows:
  2997. ```javascript
  2998. it('Can contain custom validation rules, and will trigger an error event on failed validation.', function() {
  2999. var errorCallback = jasmine.createSpy('-error event callback-');
  3000. var todo = new Todo();
  3001. todo.on('error', errorCallback);
  3002. // What would you need to set on the todo properties to
  3003. // cause validation to fail?
  3004. todo.set({done:'a non-integer value'});
  3005. var errorArgs = errorCallback.mostRecentCall.args;
  3006. expect(errorArgs).toBeDefined();
  3007. expect(errorArgs[0]).toBe(todo);
  3008. expect(errorArgs[1]).toBe('Todo.done must be a boolean value.');
  3009. });
  3010. ```
  3011. The code to make the above failing test support validation is relatively simple. In our model, we override the validate() method (as recommended in the Backbone docs), checking to make sure a model both has a 'done' property and is a valid boolean before allowing it to pass.
  3012. ```javascript
  3013. validate: function(attrs) {
  3014. if (attrs.hasOwnProperty('done') && !_.isBoolean(attrs.done)) {
  3015. return 'Todo.done must be a boolean value.';
  3016. }
  3017. }
  3018. ```
  3019. If you would like to review the final code for our Todo model, you can find it below:
  3020. ```javascript
  3021. var NAUGHTY_WORDS = /crap|poop|hell|frogs/gi;
  3022. function sanitize(str) {
  3023. return str.replace(NAUGHTY_WORDS, 'rainbows');
  3024. }
  3025. window.Todo = Backbone.Model.extend({
  3026. defaults: function() {
  3027. return {
  3028. text: '',
  3029. done: false,
  3030. order: 0
  3031. };
  3032. },
  3033. initialize: function() {
  3034. this.set({text: sanitize(this.get('text'))}, {silent: true});
  3035. },
  3036. validate: function(attrs) {
  3037. if (attrs.hasOwnProperty('done') && !_.isBoolean(attrs.done)) {
  3038. return 'Todo.done must be a boolean value.';
  3039. }
  3040. },
  3041. toggle: function() {
  3042. this.save({done: !this.get("done")});
  3043. }
  3044. });
  3045. ```
  3046. ##<a name="testing-jasmine-collections">Collections</a>
  3047. We now need to define specs to tests a Backbone collection of Todo models (a TodoList). Collections are responsible for a number of list tasks including managing order and filtering.
  3048. A few specific specs that come to mind when working with collections are:
  3049. * Making sure we can add new Todo models as both objects and arrays
  3050. * Attribute testing to make sure attributes such as the base URL of the collection are values we expect
  3051. * Purposefully adding items with a status of ```done:true``` and checking against how many items the collection thinks have been completed vs. those that are remaining
  3052. In this section we're going to cover the first two of these with the third left as an extended exercise I recommend trying out.
  3053. Testing Todo models can be added to a collection as objects or arrays is relatively trivial. First, we initialize a new TodoList collection and check to make sure it's length (i.e the number of Todo models it contains) is 0. Next, we add new Todos, both as objects and arrays, checking the length property of the collection at each stage to ensure the overall count is what we expect:
  3054. ```javascript
  3055. describe('Tests for TodoList', function() {
  3056. it('Can add Model instances as objects and arrays.', function() {
  3057. var todos = new TodoList();
  3058. expect(todos.length).toBe(0);
  3059. todos.add({ text: 'Clean the kitchen' });
  3060. // how many todos have been added so far?
  3061. expect(todos.length).toBe(1);
  3062. todos.add([
  3063. { text: 'Do the laundry', done: true },
  3064. { text: 'Go to the gym'}
  3065. ]);
  3066. // how many are there in total now?
  3067. expect(todos.length).toBe(3);
  3068. });
  3069. ...
  3070. ```
  3071. Similar to model attributes, it's also quite straight-forward to test attributes in collections. Here we have a spec that ensures the collection.url (i.e the url reference to the collection's location on the server) is what we expect it to be:
  3072. ```javascript
  3073. it('Can have a url property to define the basic url structure for all contained models.', function() {
  3074. var todos = new TodoList();
  3075. // what has been specified as the url base in our model?
  3076. expect(todos.url).toBe('/todos/');
  3077. });
  3078. ```
  3079. For the third spec, it's useful to remember that the implementation for our collection will have methods for filtering how many Todo items are done and how many are remaining - we can call these ```done()``` and ```remaining()```. Consider writing a spec which creates a new collection and adds one new model that has a preset ```done``` state of ```true``` and two others that have the default ```done``` state of ```false```. Testing the length of what's returned using ```done()``` and ```remaining()``` should allow us to know whether the state management in our application is working or needs a little tweaking.
  3080. The final implementation for our TodoList collection can be found below:
  3081. ```javascript
  3082. window.TodoList = Backbone.Collection.extend({
  3083. model: Todo,
  3084. url: '/todos/',
  3085. done: function() {
  3086. return this.filter(function(todo) { return todo.get('done'); });
  3087. },
  3088. remaining: function() {
  3089. return this.without.apply(this, this.done());
  3090. },
  3091. nextOrder: function() {
  3092. if (!this.length) {
  3093. return 1;
  3094. }
  3095. return this.last().get('order') + 1;
  3096. },
  3097. comparator: function(todo) {
  3098. return todo.get('order');
  3099. }
  3100. });
  3101. ```
  3102. ##<a name="testing-jasmine-views">Views</a>
  3103. Before we take a look at testing Backbone views, let's briefly review a jQuery plugin that can assist with writing Jasmine specs for them.
  3104. **The Jasmine jQuery Plugin**
  3105. As we know our Todo application will be using jQuery for DOM manipulation, there's a useful jQuery plugin called [jasmine-jquery](https://github.com/velesin/jasmine-jquery) we can use to help simplify BDD testing rendered elements that our views may produce.
  3106. The plugin provides a number of additional Jasmine [matchers](https://github.com/pivotal/jasmine/wiki/Matchers) to help test jQuery wrapped sets such as:
  3107. * ```toBe(jQuerySelector)``` e.g ```expect($('<div id="some-id"></div>')).toBe('div#some-id')```
  3108. * ```toBeChecked()``` e.g ```expect($('<input type="checkbox" checked="checked"/>')).toBeChecked()```
  3109. * ```toBeSelected()``` e.g ```expect($('<option selected="selected"></option>')).toBeSelected()```
  3110. and [many others](https://github.com/velesin/jasmine-jquery). The complete list of matchers supported can be found on the project homepage. It's useful to know that similar to the standard Jasmine matchers, the custom matchers above can be inverted using the .not prefix (i.e ```expect(x).not.toBe(y)```):
  3111. ```javascript
  3112. expect($('<div>I am an example</div>')).not.toHaveText(/other/)
  3113. ```
  3114. jasmine-jquery also includes a fixtures model, allowing us to load in arbitrary HTML content we may wish to use in our tests. Fixtures can be used as follows:
  3115. Include some HTML in an external fixtures file:
  3116. some.fixture.html:
  3117. ```<div id="sample-fixture">some HTML content</div>```
  3118. Next, inside our actual test we would load it as follows:
  3119. ```javascript
  3120. loadFixtures('some.fixture.html')
  3121. $('some-fixture').myTestedPlugin();
  3122. expect($('#some-fixture')).to<the rest of your matcher would go here>
  3123. ```
  3124. The jasmine-jquery plugin is by default setup to load fixtures from a specific directory: spec/javascripts/fixtures. If you wish to configure this path you can do so by initially setting ```jasmine.getFixtures().fixturesPath = 'your custom path'```.
  3125. Finally, jasmine-jquery includes support for spying on jQuery events without the need for any extra plumbing work. This can be done using the ```spyOnEvent()``` and ```assert(eventName).toHaveBeenTriggered(selector)``` functions. An example of usage may look as follows:
  3126. ```javascript
  3127. spyOnEvent($('#el'), 'click');
  3128. $('#el').click();
  3129. expect('click').toHaveBeenTriggeredOn($('#el'));
  3130. ```
  3131. **View testing**
  3132. In this section we will review three dimensions to writing specs for Backbone Views: initial setup, view rendering and finally templating. The latter two of these are the most commonly tested, however we'll review shortly why writing specs for the initialization of your views can also be of benefit.
  3133. ##Initial setup
  3134. At their most basic, specs for Backbone views should validate that they are being correctly tied to specific DOM elements and are backed by valid data models. The reason to consider doing this is that failures to such specs can trip up more complex tests later on and they're fairly simple to write, given the overall value offered.
  3135. To help ensure a consistent testing setup for our specs, we use ```beforeEach()``` to append both an empty ```UL``` (#todoList) to the DOM and initialize a new instance of a TodoView using an empty Todo model. ```afterEach()``` is used to remove the previous #todoList ```UL``` as well as the previous instance of the view.
  3136. ```javascript
  3137. describe('Tests for TodoView', function() {
  3138. beforeEach(function() {
  3139. $('body').append('<ul id="todoList"></ul>');
  3140. this.todoView = new TodoView({ model: new Todo() });
  3141. });
  3142. afterEach(function() {
  3143. this.todoView.remove();
  3144. $('#todoList').remove();
  3145. });
  3146. ...
  3147. ```
  3148. The first spec useful to write is a check that the TodoView we've created is using the correct ```tagName``` (element or className). The purpose of this test is to make sure it's been correctly tied to a DOM element when it was created.
  3149. Backbone views typically create empty DOM elements once initialized, however these elements are not attached to the visible DOM in order to allow them to be constructed without an impact on the performance of rendering.
  3150. ```javascript
  3151. it('Should be tied to a DOM element when created, based off the property provided.', function() {
  3152. //what html element tag name represents this view?
  3153. expect(todoView.el.tagName.toLowerCase()).toBe('li');
  3154. });
  3155. ```
  3156. Once again, if the TodoView has not already been written, we will experience failing specs. Thankfully, solving this is as simple as creating a new Backbone.View with a specific ```tagName```.
  3157. ```javascript
  3158. var todoView = Backbone.View.extend({
  3159. tagName: "li"
  3160. });
  3161. ```
  3162. If instead of testing against the ```tagName``` you would prefer to use a className instead, we can take advantage of jasmine-jquery's ```toHaveClass()``` matcher to cater for this.
  3163. ```
  3164. it('Should have a class of "todos"'), function(){
  3165. expect(this.view.$el).toHaveClass('todos');
  3166. });
  3167. ```
  3168. The ```toHaveClass()``` matcher operates on jQuery objects and if the plugin hadn't been used, an exception would have been incurred (it is of course also possible to test for the className by accessing el.className if not opting to use jasmine-jquery).
  3169. You may have noticed that in ```beforeEach()```, we passed our view an initial (albeit unfilled) Todo model. Views should be backed by a model instance which provides data. As this is quite important to our view's ability to function, we can write a spec to ensure a model is both defined (using the ```toBeDefined()``` matcher) and then test attributes of the model to ensure defaults both exist and are the value we expect them to be.
  3170. ```javascript
  3171. it('Is backed by a model instance, which provides the data.', function() {
  3172. expect(todoView.model).toBeDefined();
  3173. // what's the value for Todo.get('done') here?
  3174. expect(todoView.model.get('done')).toBe(false); //or toBeFalsy()
  3175. });
  3176. ```
  3177. ##View rendering
  3178. Next we're going to take a look at writing specs for view rendering. Specifically, we want to test that our TodoView elements are actually rendering as expected.
  3179. In smaller applications, those new to BDD might argue that visual confirmation of view rendering could replace unit testing of views. The reality is that when dealing with applications that might grow to multiple-views, it often makes sense to automate this process as much as possible from the get-go. There are also aspects of rendering that require verification beyond what is visually presented on-screen (which we'll see very shortly).
  3180. We're going to begin testing views by writing two specs. The first spec will check that the view's ```render()``` method is correctly returning the view instance, which is necessary for chaining. Our second spec will check that the HTML produced is exactly what we expect based on the properties of the model instance that's been associated with our TodoView.
  3181. Unlike some of the previous specs we've covered, this section will make greater use of ```beforeEach()``` to both demonstrate how to use nested suites and also ensure a consistent set of conditions for our specs. In our first view spec for TodoView, we're simply going to create a sample model (based on Todo) and instantiate a TodoView which associates it with the model.
  3182. ```javascript
  3183. describe("TodoView", function() {
  3184. beforeEach(function() {
  3185. this.model = new Backbone.Model({
  3186. text: "My Todo",
  3187. order: 1,
  3188. done: false
  3189. });
  3190. this.view = new TodoView({model:this.model});
  3191. });
  3192. describe("Rendering", function() {
  3193. it("returns the view object", function() {
  3194. expect(this.view.render()).toEqual(this.view);
  3195. });
  3196. it("produces the correct HTML", function() {
  3197. this.view.render();
  3198. //let's use jasmine-jquery's toContain() to avoid
  3199. //testing for the complete content of a todo's markup
  3200. expect(this.view.el.innerHTML)
  3201. .toContain('<label class="todo-content">My Todo</label>');
  3202. });
  3203. });
  3204. });
  3205. ```
  3206. Once these specs are run, only the second one ('produces the correct HTML') fails. Our first spec ('returns the view object'), which is testing that the TodoView instance is returned from ```render()```, only passed as this is Backbone's default behavior. We haven't yet overwritten the ```render()``` method with our own version.
  3207. **Note:** For the purposes of maintaining readability, all template examples in this section will use a minimal version of the following Todo view template. As it's relatively trivial to expand this, please feel free to refer to this sample if needed:
  3208. <div class="todo <%= done ? 'done' : '' %>">
  3209. <div class="display">
  3210. <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
  3211. <label class="todo-content"><%= text %></label>
  3212. <span class="todo-destroy"></span>
  3213. </div>
  3214. <div class="edit">
  3215. <input class="todo-input" type="text" value="<%= content %>" />
  3216. </div>
  3217. </div>
  3218. The second spec fails with the following message:
  3219. Expected '' to contain ```'<label class="todo-content">My Todo</label>'```.
  3220. The reason for this is the default behavior for render() doesn't create any markup. Let's write a replacement for render() which fixes this:
  3221. ```javascript
  3222. render: function() {
  3223. var template = '<label class="todo-content"><%= text %></label>';
  3224. var output = template
  3225. .replace("<%= text %>", this.model.get('text'));
  3226. this.$el.html(output);
  3227. return this;
  3228. }
  3229. ```
  3230. The above specifies an inline string template and replaces fields found in the template within the "<% %>" blocks with their corresponding values from the associated model. As we're now also returning the TodoView instance from the method, the first spec will also pass. It's worth noting that there are serious drawbacks to using HTML strings in your specs to test against like this. Even minor changes to your template (a simple tab or whitespace) would cause your spec to fail, despite the rendered output being the same. It's also more time consuming to maintain as most templates in real-world applications are significantly more complex. A better option for testing rendered output is using jQuery to both select and inspect values.
  3231. With this in mind, let's re-write the specs, this time using some of the custom matchers offered by jasmine-jquery:
  3232. ```javascript
  3233. describe("Template", function() {
  3234. beforeEach(function() {
  3235. this.view.render();
  3236. });
  3237. it("has the correct text content", function() {
  3238. expect(this.view.$('.todo-content'))
  3239. .toHaveText('My Todo');
  3240. });
  3241. });
  3242. ```
  3243. It would be impossible to discuss unit testing without mentioning fixtures. Fixtures typically contain test data (e.g HTML) that is loaded in when needed (either locally or from an external file) for unit testing. So far we've been establishing jQuery expectations based on the view's el property. This works for a number of cases, however, there are instances where it may be necessary to render markup into the document. The most optimal way to handle this within specs is through using fixtures (another feature brought to us by the jasmine-jquery plugin).
  3244. Re-writing the last spec to use fixtures would look as follows:
  3245. ```javascript
  3246. describe("TodoView", function() {
  3247. beforeEach(function() {
  3248. ...
  3249. setFixtures('<ul class="todos"></ul>');
  3250. });
  3251. ...
  3252. describe("Template", function() {
  3253. beforeEach(function() {
  3254. $('.todos').append(this.view.render().el);
  3255. });
  3256. it("has the correct text content", function() {
  3257. expect($('.todos').find('.todo-content'))
  3258. .toHaveText('My Todo');
  3259. });
  3260. });
  3261. });
  3262. ```
  3263. What we're now doing in the above spec is appending the rendered todo item into the fixture. We then set expectations against the fixture, which may be something desirable when a view is setup against an element which already exists in the DOM. It would be necessary to provide both the fixture and test the ```el``` property correctly picking up the element expected when the view is instantiated.
  3264. ##Rendering with a templating system
  3265. JavaScript templating systems (such as Handlebars, Mustache and even Underscore's own Micro-templating) support conditional logic in template strings. What this effectively means is that we can add if/else/ternery expressions inline which can then be evaluated as needed, allowing us to build even more powerful templates.
  3266. In our case, when a user sets a Todo item to be complete (done), we may wish to provide them with visual feedback (such as a striked line through the text) to differentiate the item from those that are remaining. This can be done by attaching a new class to the item. Let's begin by writing a test we would ideally like to work:
  3267. ```javascript
  3268. describe("When a todo is done", function() {
  3269. beforeEach(function() {
  3270. this.model.set({done: true}, {silent: true});
  3271. $('.todos').append(this.view.render().el);
  3272. });
  3273. it("has a done class", function() {
  3274. expect($('.todos .todo-content:first-child'))
  3275. .toHaveClass("done");
  3276. });
  3277. });
  3278. ```
  3279. This will fail with the following message:
  3280. Expected '<label class="todo-content">My Todo</label>'
  3281. to have class 'done'.
  3282. which can be fixed in the existing render() method as follows:
  3283. ```javascript
  3284. render: function() {
  3285. var template = '<label class="todo-content">' +
  3286. '<%= text %></label>';
  3287. var output = template
  3288. .replace("<%= text %>", this.model.get('text'));
  3289. this.$el.html(output);
  3290. if (this.model.get('done')) {
  3291. this.$(".todo-content").addClass("done");
  3292. }
  3293. return this;
  3294. }
  3295. ```
  3296. This can however get unwieldily fairly quickly. As the logic in our templates increases, so does the complexity involved. This is where templates libraries can help. As mentioned earlier, there are a number of popular options available, but for the purposes of this chapter we're going to stick to using Underscore's built-in Microtemplating. Whilst there are more advanced options you're free to explore, the benefit of this is that no additional files are required and we can easily change the existing Jasmine specs without too much adjustment.
  3297. The TodoView object modified to use Underscore templating would look as follows:
  3298. ```javascript
  3299. var TodoView = Backbone.View.extend({
  3300. tagName: "li",
  3301. initialize: function(options) {
  3302. this.template = _.template(options.template || "");
  3303. },
  3304. render: function() {
  3305. this.$el.html(this.template(this.model.toJSON()));
  3306. return this;
  3307. },
  3308. ...
  3309. });
  3310. ```
  3311. Above, the initialize() method compiles a supplied Underscore template (using the _.template() function) in the instantiation. A more common way of referencing templates is placing them in a script tag using a custom script type (e.g type="text/template"). As this isn't a script type any browser understands, it's simply ignored, however referencing the script by an id attribute allows the template to be kept separate to other parts of the page which wish to use it. In real world applications, it's preferable to either do this or load in templates stored in external files for testing.
  3312. For testing purposes, we're going to continue using the string injection approach to keep things simple. There is however a useful trick that can be applied to automatically create or extend templates in the Jasmine scope for each test. By creating a new directory (say, 'templates') in the 'spec' folder and adding a new script file with the following contents, to jasmine.yml or SpecRunner.html, we can add a todo property which contains the Underscore template we wish to use:
  3313. ```javascript
  3314. beforeEach(function() {
  3315. this.templates = _.extend(this.templates || {}, {
  3316. todo: '<label class="todo-content">' +
  3317. '<%= text %>' +
  3318. '</label>'
  3319. });
  3320. });
  3321. ```
  3322. To finish this off, we simply update our existing spec to reference the template when instantiating the TodoView object:
  3323. ```javascript
  3324. describe("TodoView", function() {
  3325. beforeEach(function() {
  3326. ...
  3327. this.view = new TodoView({
  3328. model: this.model,
  3329. template: this.templates.todo
  3330. });
  3331. });
  3332. ...
  3333. });
  3334. ```
  3335. The existing specs we've looked at would continue to pass using this approach, leaving us free to adjust the template with some additional conditional logic for Todos with a status of 'done':
  3336. ```javascript
  3337. beforeEach(function() {
  3338. this.templates = _.extend(this.templates || {}, {
  3339. todo: '<label class="todo-content <%= done ? 'done' : '' %>"' +
  3340. '<%= text %>' +
  3341. '</label>'
  3342. });
  3343. });
  3344. ```
  3345. This will now also pass without any issues. Remember that jasmine-jquery also supports loading external fixtures into your specs easily using it's build in ```loadFixtures()``` and ```readFixtures()``` methods. For more information, consider reading the official jasmine-jquery [docs](https://github.com/velesin/jasmine-jquery).
  3346. ##Conclusions
  3347. We have now covered how to write Jasmine tests for models, views and collections with Backbone.js. Whilst testing routing can at times be desirable, some developers feel it can be more optimal to leave this to third-party tools such as Selenium, so do keep this in mind.
  3348. James Newbery was kind enough to help me with writing the Views section above and his articles on [Testing Backbone Apps With SinonJS](http://tinnedfruit.com/2011/04/26/testing-backbone-apps-with-jasmine-sinon-3.html) were of great inspiration (you'll actually find some Handlebars examples of the view specs in part 3 of his article). If you would like to learn more about writing spies and mocks for Backbone using [SinonJS](http://sinonjs.org) as well as how to test Backbone routers, do consider reading his series.
  3349. ##Exercise
  3350. As an exercise, I recommend now trying the Jasmine Koans in `practicals\jasmine-joans` and trying to fix some of the purposefully failing tests it has to offer. This is an excellent way of not just learning how Jasmine specs and suites work, but working through the examples (without peaking back) will also put your Backbone skills to test too.
  3351. ##Further reading
  3352. * [Jasmine + Backbone Revisited](http://japhr.blogspot.com/2011/11/jasmine-backbonejs-revisited.html)
  3353. * [Backbone, PhantomJS and Jasmine](http://japhr.blogspot.com/2011/12/phantomjs-and-backbonejs-and-requirejs.html)
  3354. #<a name="unittestingqunit">Unit Testing Backbone Applications With QUnit And SinonJS</a>
  3355. ##Introduction
  3356. QUnit is a powerful JavaScript test suite written by jQuery team member [Jörn Zaefferer](http://bassistance.de/) and used by many large open-source projects (such as jQuery and Backbone.js) to test their code. It's both capable of testing standard JavaScript code in the browser as well as code on the server-side (where environments supported include Rhino, V8 and SpiderMonkey). This makes it a robust solution for a large number of use-cases.
  3357. Quite a few Backbone.js contributors feel that QUnit is a better introductory framework for testing if you don't wish to start off with Jasmine and BDD right away. As we'll see later on in this chapter, QUnit can also be combined with third-party solutions such as SinonJS to produce an even more powerful testing solution supporting spies and mocks, which some say is preferable over Jasmine.
  3358. My personal recommendation is that it's worth comparing both frameworks and opting for the solution that you feel the most comfortable with.
  3359. #QUnit
  3360. ##Getting Setup
  3361. Luckily, getting QUnit setup is a fairly straight-forward process that will take less than 5 minutes.
  3362. We first setup a testing environment composed of three files:
  3363. * A HTML **structure** for displaying test results,
  3364. * The **qunit.js** file composing the testing framework and,
  3365. * The **qunit.css** file for styling test results.
  3366. The latter two of these can be downloaded from the [QUnit website](http://qunitjs.com).
  3367. If you would prefer, you can use a hosted version of the QUnit source files for testing purposes. The hosted URLs can be found at [http://github.com/jquery/qunit/raw/master/qunit/].
  3368. ####Sample HTML with QUnit-compatible markup:
  3369. ```html
  3370. <!DOCTYPE html>
  3371. <html>
  3372. <head>
  3373. <title>QUnit Test Suite</title>
  3374. <link rel="stylesheet" href="qunit.css">
  3375. <script src="qunit.js"></script>
  3376. <!-- Your application -->
  3377. <script src="app.js"></script>
  3378. <!-- Your tests -->
  3379. <script src="tests.js"></script>
  3380. </head>
  3381. <body>
  3382. <h1 id="qunit-header">QUnit Test Suite</h1>
  3383. <h2 id="qunit-banner"></h2>
  3384. <div id="qunit-testrunner-toolbar"></div>
  3385. <h2 id="qunit-userAgent"></h2>
  3386. <ol id="qunit-tests">test markup, hidden.</ol>
  3387. </body>
  3388. </html>
  3389. ```
  3390. Let's go through the elements above with qunit mentioned in their ID. When QUnit is running:
  3391. * **qunit-header** shows the name of the test suite
  3392. * **qunit-banner** shows up as red if a test fails and green if all tests pass
  3393. * **qunit-testrunner-toolbar** contains additional options for configuring the display of tests
  3394. * **qunit-userAgent** displays the navigator.userAgent property
  3395. * **qunit-tests** is a container for our test results
  3396. When running correctly, the above test runner looks as follows:
  3397. ![screenshot 1](img/7d4de12.png)
  3398. The numbers of the form (a, b, c) after each test name correspond to a) failed asserts, b) passed asserts and c) total asserts. Clicking on a test name expands it to display all of the assertions for that test case. Assertions in green have successfully passed.
  3399. ![screenshot 2](img/9df4.png)
  3400. If however any tests fail, the test gets highlighted (and the qunit-banner at the top switches to red):
  3401. ![screenshot 3](img/3e5545.png)
  3402. ##Assertions
  3403. QUnit supports a number of basic **assertions**, which are used in testing to verify that the result being returned by our code is what we expect. If an assertion fails, we know that a bug exists.Similar to Jasmine, QUnit can be used to easily test for regressions. Specifically, when a bug is found one can write an assertion to test the existence of the bug, write a patch and then commit both. If subsequent changes to the code break the test you'll know what was responsible and be able to address it more easily.
  3404. Some of the supported QUnit assertions we're going to look at first are:
  3405. * `ok ( state, message )` - passes if the first argument is truthy
  3406. * `equal ( actual, expected, message )` - a simple comparison assertion with type coercion
  3407. * `notEqual ( actual, expected, message )` - the opposite of the above
  3408. * `expect( amount )` - the number of assertions expected to run within each test
  3409. * `strictEqual( actual, expected, message)` - offers a much stricter comparison than `equal()` and is considered the preferred method of checking equality as it avoids stumbling on subtle coercion bugs
  3410. * `deepEqual( actual, expected, message )` - similar to `strictEqual`, comparing the contents (with `===`) of the given objects, arrays and primitives.
  3411. Creating new test cases with QUnit is relatively straight-forward and can be done using ```test()```, which constructs a test where the first argument is the ```name``` of the test to be displayed in our results and the second is a ```callback``` function containing all of our assertions. This is called as soon as QUnit is running.
  3412. ####Basic test case using test( name, callback ):
  3413. ```javascript
  3414. var myString = 'Hello Backbone.js';
  3415. test( 'Our first QUnit test - asserting results', function(){
  3416. // ok( boolean, message )
  3417. ok( true, 'the test succeeds');
  3418. ok( false, 'the test fails');
  3419. // equal( actualValue, expectedValue, message )
  3420. equal( myString, 'Hello Backbone.js', 'The value expected is Hello Backbone.js!');
  3421. });
  3422. ```
  3423. What we're doing in the above is defining a variable with a specific value and then testing to ensure the value was what we expected it to be. This was done using the comparison assertion, ```equal()```, which expects its first argument to be a value being tested and the second argument to be the expected value. We also used ```ok()```, which allows us to easily test against functions or variables that evaluate to booleans.
  3424. Note: Optionally in our test case, we could have passed an 'expected' value to ```test()``` defining the number of assertions we expect to run. This takes the form: `test( name, [expected], test );` or by manually settings the expectation at the top of the test function, like so: `expect( 1 )`. I recommend you to make it a habit and always define how many assertions you expect. More on this later.
  3425. As testing a simple static variable is fairly trivial, we can take this further to test actual functions. In the following example we test the output of a function that reverses a string to ensure that the output is correct using ```equal()``` and ```notEqual()```:
  3426. ####Comparing the actual output of a function against the expected output:
  3427. ```javascript
  3428. function reverseString( str ){
  3429. return str.split("").reverse().join("");
  3430. }
  3431. test( 'reverseString()', function() {
  3432. expect( 5 );
  3433. equal( reverseString('hello'), 'olleh', 'The value expected was olleh' );
  3434. equal( reverseString('foobar'), 'raboof', 'The value expected was raboof' );
  3435. equal( reverseString('world'), 'dlrow', 'The value expected was dlrow' );
  3436. notEqual( reverseString('world'), 'dlroo', 'The value was expected to not be dlroo' );
  3437. equal( reverseString('bubble'), 'double', 'The value expected was elbbub' );
  3438. })
  3439. ```
  3440. Running these tests in the QUnit test runner (which you would see when your HTML test page was loaded) we would find that four of the assertions pass whilst the last one does not. The reason the test against `'double'` fails is because it was purposefully written incorrectly. In your own projects if a test fails to pass and your assertions are correct, you've probably just found a bug!
  3441. ##Adding structure to assertions
  3442. Housing all of our assertions in one test case can quickly become difficult to maintain, but luckily QUnit supports structuring blocks of assertions more cleanly. This can be done using ```module()``` - a method that allows us to easily group tests together. A typical approach to grouping might be keeping multiple tests testing a specific method as part of the same group (module).
  3443. ####Basic QUnit Modules:
  3444. ```javascript
  3445. module( 'Module One' );
  3446. test( 'first test', function() {} );
  3447. test( 'another test', function() {} );
  3448. module( 'Module Two' );
  3449. test( 'second test', function() {} );
  3450. test( 'another test', function() {} );
  3451. module( 'Module Three' );
  3452. test( 'third test', function() {} );
  3453. test( 'another test', function() {} );
  3454. ```
  3455. We can take this further by introducing ```setup()``` and ```teardown()``` callbacks to our modules, where ```setup()``` is run before each test whilst ```teardown()``` is run after each test.
  3456. ####Using setup() and teardown() :
  3457. ```javascript
  3458. module( "Module One", {
  3459. setup: function() {
  3460. // run before
  3461. },
  3462. teardown: function() {
  3463. // run after
  3464. }
  3465. });
  3466. test("first test", function() {
  3467. // run the first test
  3468. });
  3469. ```
  3470. These callbacks can be used to define (or clear) any components we wish to instantiate for use in one or more of our tests. As we'll see shortly, this is ideal for defining new instances of views, collections, models or routers from a project that we can then reference across multiple tests.
  3471. ####Using setup() and teardown() for instantiation and clean-up:
  3472. ```javascript
  3473. // Define a simple model and collection modeling a store and
  3474. // list of stores
  3475. var Store = Backbone.Model.extend({});
  3476. var StoreList = Backbone.Collection.extend({
  3477. model: store,
  3478. comparator: function( store ) { return store.get('name') }
  3479. });
  3480. // Define a group for our tests
  3481. module( "StoreList sanity check", {
  3482. setup: function() {
  3483. this.list = new StoreList;
  3484. this.list.add(new Store({ name: "Costcutter" }));
  3485. this.list.add(new Store({ name: "Target" }));
  3486. this.list.add(new Store({ name: "Walmart" }));
  3487. this.list.add(new Store({ name: "Barnes & Noble" });
  3488. },
  3489. teardown: function() {
  3490. window.errors = null;
  3491. }
  3492. });
  3493. // Test the order of items added
  3494. test( "test ordering", function() {
  3495. expect( 1 );
  3496. var expected = ["Barnes & Noble", "Costcutter", "Target", "Walmart"];
  3497. var actual = this.list.pluck("name");
  3498. deepEqual( actual, expected, "is maintained by comparator" );
  3499. });
  3500. ```
  3501. Here, a list of stores is created and stored on ```setup()```. A ```teardown()``` callback is used to simply clear our a list of errors we might be storing within the window scope, but is otherwise not needed.
  3502. ##Assertion examples
  3503. Before we continue any further, let's review some more examples of how QUnits various assertions can be correctly used when writing tests:
  3504. ###equal - a comparison assertion. It passes if actual == expected
  3505. ```javascript
  3506. test( "equal", 2, function() {
  3507. var actual = 6 - 5;
  3508. equal( actual, true, "passes as 1 == true" );
  3509. equal( actual, 1, "passes as 1 == 1" );
  3510. });
  3511. ```
  3512. ###notEqual - a comparison assertion. It passes if actual != expected
  3513. ```javascript
  3514. test( "notEqual", 2, function() {
  3515. var actual = 6 - 5;
  3516. notEqual( actual, false, "passes as 1 != false" );
  3517. notEqual( actual, 0, "passes as 1 != 0" );
  3518. });
  3519. ```
  3520. ###strictEqual - a comparison assertion. It passes if actual === expected.
  3521. ```javascript
  3522. test( "strictEqual", 2, function() {
  3523. var actual = 6 - 5;
  3524. strictEqual( actual, true, "fails as 1 !== true" );
  3525. strictEqual( actual, 1, "passes as 1 === 1" );
  3526. });
  3527. ```
  3528. ###notStrictEqual - a comparison assertion. It passes if actual !== expected.
  3529. ```javascript
  3530. test("notStrictEqual", 2, function() {
  3531. var actual = 6 - 5;
  3532. notStrictEqual( actual, true, "passes as 1 !== true" );
  3533. notStrictEqual( actual, 1, "fails as 1 === 1" );
  3534. });
  3535. ```
  3536. ###deepEqual - a recursive comparison assertion. Unlike strictEqual(), it works on objects, arrays and primitives.
  3537. ```javascript
  3538. test("deepEqual", 4, function() {
  3539. var actual = {q: 'foo', t: 'bar'};
  3540. var el = $('div');
  3541. var children = $('div').children();
  3542. equal( actual, {q: 'foo', t: 'bar'}, "fails - objects are not equal using equal()" );
  3543. deepEqual( actual, {q: 'foo', t: 'bar'}, "passes - objects are equal" );
  3544. equal( el, children, "fails - jQuery objects are not the same" );
  3545. deepEqual(el, children, "fails - objects not equivalent" );
  3546. });
  3547. ```
  3548. ###notDeepEqual - a comparison assertion. This returns the opposite of deepEqual
  3549. ```javascript
  3550. test("notDeepEqual", 2, function() {
  3551. var actual = {q: 'foo', t: 'bar'};
  3552. notEqual( actual, {q: 'foo', t: 'bar'}, "passes - objects are not equal" );
  3553. notDeepEqual( actual, {q: 'foo', t: 'bar'}, "fails - objects are equivalent" );
  3554. });
  3555. ```
  3556. ###raises - an assertion which tests if a callback throws any exceptions
  3557. ```javascript
  3558. test("raises", 1, function() {
  3559. raises(function() {
  3560. throw new Error( "Oh no! It's an error!" );
  3561. }, "passes - an error was thrown inside our callback");
  3562. });
  3563. ```
  3564. ##Fixtures
  3565. From time to time we may need to write tests that modify the DOM. Managing the clean-up of such operations between tests can be a genuine pain, but thankfully QUnit has a solution to this problem in the form of the `#qunit-fixture` element, seen below.
  3566. ####Fixture markup:
  3567. ```html
  3568. <!DOCTYPE html>
  3569. <html>
  3570. <head>
  3571. <title>QUnit Test</title>
  3572. <link rel="stylesheet" href="qunit.css">
  3573. <script src="qunit.js"></script>
  3574. <script src="app.js"></script>
  3575. <script src="tests.js"></script>
  3576. </head>
  3577. <body>
  3578. <h1 id="qunit-header">QUnit Test</h1>
  3579. <h2 id="qunit-banner"></h2>
  3580. <div id="qunit-testrunner-toolbar"></div>
  3581. <h2 id="qunit-userAgent"></h2>
  3582. <ol id="qunit-tests"></ol>
  3583. <div id="qunit-fixture"></div>
  3584. </body>
  3585. </html>
  3586. ```
  3587. We can either opt to place static markup in the fixture or just insert/append any DOM elements we may need to it. QUnit will automatically reset the `innerHTML` of the fixture after each test to its original value. In case you're using jQuery, it's useful to know that QUnit checks for its availability and will opt to use ```$(el).html()``` instead, which will cleanup any jQuery event handlers too.
  3588. ###Fixtures example:
  3589. Let us now go through a more complete example of using fixtures. One thing that most of us are used to doing in jQuery is working with lists - they're often used to define the markup for menus, grids and a number of other components. You may have used jQuery plugins before that manipulated a given list in a particular way and it can be useful to test that the final (manipulated) output of the plugin is what was expected.
  3590. For the purposes of our next example, we're going to use Ben Alman's `$.enumerate()` plugin, which can prepend each item in a list by its index, optionally allowing us to set what the first number in the list is. The code snippet for the plugin can be found below, followed by an example of the output is generates:
  3591. ```javascript
  3592. $.fn.enumerate = function( start ) {
  3593. if ( typeof start !== "undefined" ) {
  3594. // Since `start` value was provided, enumerate and return
  3595. // the initial jQuery object to allow chaining.
  3596. return this.each(function(i){
  3597. $(this).prepend( "<b>" + ( i + start ) + "</b> " );
  3598. });
  3599. } else {
  3600. // Since no `start` value was provided, function as a
  3601. // getter, returing the appropriate value from the first
  3602. // selected element.
  3603. var val = this.eq( 0 ).children( "b" ).eq( 0 ).text();
  3604. return Number( val );
  3605. }
  3606. };
  3607. /*
  3608. <ul>
  3609. <li>1. hello</li>
  3610. <li>2. world</li>
  3611. <li>3. i</li>
  3612. <li>4. am</li>
  3613. <li>5. foo</li>
  3614. </ul>
  3615. */
  3616. ```
  3617. Let's now write some specs for the plugin. First, we define the markup for a list containing some sample items inside our ```qunit-fixture``` element:
  3618. ```html
  3619. &lt;div id=&quot;qunit-fixture&quot;&gt;
  3620. &lt;ul&gt;
  3621. &lt;li&gt;hello&lt;/li&gt;
  3622. &lt;li&gt;world&lt;/li&gt;
  3623. &lt;li&gt;i&lt;/li&gt;
  3624. &lt;li&gt;am&lt;/li&gt;
  3625. &lt;li&gt;foo&lt;/li&gt;
  3626. &lt;/ul&gt;
  3627. &lt;/div&gt;
  3628. ```
  3629. Next, we need to think about what should be tested. `$.enumerate()` supports a few different use cases, including:
  3630. * **No arguments passed** - i.e ```$(el).enumerate()```
  3631. * **0 passed as an argument** - i.e ```$(el).enumerate(0)```
  3632. * **1 passed as an argument** - i.e ```$(el).enumerate(1)```
  3633. As the text value for each list item is of the form "n. item-text" and we only require this to test against the expected output, we can simply access the content using ```$(el).eq(index).text()``` (for more information on .eq() see [here](http://api.jquery.com/eq/)).
  3634. and finally, here are our test cases:
  3635. ```javascript
  3636. module("jQuery#enumerate");
  3637. test( "No arguments passed", 5, function() {
  3638. var items = $("#qunit-fixture li").enumerate();
  3639. equal( items.eq(0).text(), "1. hello", "first item should have index 1" );
  3640. equal( items.eq(1).text(), "2. world", "second item should have index 2" );
  3641. equal( items.eq(2).text(), "3. i", "third item should have index 3" );
  3642. equal( items.eq(3).text(), "4. am", "fourth item should have index 4" );
  3643. equal( items.eq(4).text(), "5. foo", "fifth item should have index 5" );
  3644. });
  3645. test( "0 passed as an argument", 5, function() {
  3646. var items = $("#qunit-fixture li").enumerate( 0 );
  3647. equal( items.eq(0).text(), "0. hello", "first item should have index 0" );
  3648. equal( items.eq(1).text(), "1. world", "second item should have index 1" );
  3649. equal( items.eq(2).text(), "2. i", "third item should have index 2" );
  3650. equal( items.eq(3).text(), "3. am", "fourth item should have index 3" );
  3651. equal( items.eq(4).text(), "4. foo", "fifth item should have index 4" );
  3652. });
  3653. test( "1 passed as an argument", 3, function() {
  3654. var items = $("#qunit-fixture li").enumerate( 1 );
  3655. equal( items.eq(0).text(), "1. hello", "first item should have index 1" );
  3656. equal( items.eq(1).text(), "2. world", "second item should have index 2" );
  3657. equal( items.eq(2).text(), "3. i", "third item should have index 3" );
  3658. equal( items.eq(3).text(), "4. am", "fourth item should have index 4" );
  3659. equal( items.eq(4).text(), "5. foo", "fifth item should have index 5" );
  3660. });
  3661. ```
  3662. ##Asynchronous code
  3663. As with Jasmine, the effort required to run synchronous tests with QUnit is fairly straight-forward. That said, what about tests that require asynchronous callbacks (such as expensive processes, Ajax requests and so on)? When we're dealing with asynchronous code, rather than letting QUnit control when the next test runs, we can inform that we need it to stop running and wait until it's okay to continue once again.
  3664. Remember: running asynchronous code without any special considerations can cause incorrect assertions to appear in other tests, so we want to make sure we get it right.
  3665. Writing QUnit tests for asynchronous code is made possible using the ```start()``` and ```stop()`` methods, which programmatically set the start and stop points during such tests. Here's a simple example:
  3666. ```javascript
  3667. test("An async test", function(){
  3668. stop();
  3669. expect( 1 );
  3670. $.ajax({
  3671. url: "/test",
  3672. dataType: 'json',
  3673. success: function( data ){
  3674. deepEqual(data, {
  3675. topic: "hello",
  3676. message: "hi there!"
  3677. });
  3678. start();
  3679. }
  3680. });
  3681. });
  3682. ```
  3683. A jQuery ```$.ajax()``` request is used to connect to a test resource and assert that the data returned is correct. ```deepEqual()``` is used here as it allows us to compare different data types (e.g objects, arrays) and ensures that what is returned is exactly what we're expecting. We know that our Ajax request is asynchronous and so we first call ```stop()```, run the code making the request and finally at the very end of our callback, inform QUnit that it is okay to continue running other tests.
  3684. Note: rather than including ```stop()```, we can simply exclude it and substitute ```test()``` with ```asyncTest()``` if we prefer. This improves readability when dealing with a mixture of asynchronous and synchronous tests in your suite. Whilst this setup should work fine for many use-cases, there is no guarantee that the callback in our ```$.ajax()``` request will actually get called. To factor this into our tests, we can use ```expect()``` once again to define how many assertions we expect to see within our test. This is a healthy safety blanket as it ensures that if a test completes with an insufficient number of assertions, we know something went wrong and fix it.
  3685. #SinonJS
  3686. Similar to the section on testing Backbone.js apps using the Jasmine BDD framework, we're nearly ready to take what we've learned and write a number of QUnit tests for our Todo application.
  3687. Before we start though, you may have noticed that QUnit doesn't support test spies. Test spies are functions which record arguments, exceptions and return values for any of their calls. They're typically used to test callbacks and how functions may be used in the application being tested. In testing frameworks, spies can usually be either anonymous functions or wrap functions which already exist.
  3688. ##What is SinonJS?
  3689. In order for us to substitute support for spies in QUnit, we will be taking advantage of a mocking framework called [SinonJS](http://sinonjs.org/) by Christian Johansen. We will also be using the [SinonJS-QUnit adapter](http://sinonjs.org/qunit/) which provides seamless integration with QUnit (meaning setup is minimal). Sinon.JS is completely test-framework agnostic and should be easy to use with any testing framework, so it's ideal for our needs.
  3690. The framework supports three features we'll be taking advantage of for unit testing our application:
  3691. * **Anonymous spies**
  3692. * **Spying on existing methods**
  3693. * **A rich inspection interface**
  3694. Using ```this.spy()``` without any arguments creates an anonymous spy. This is comparable to ```jasmine.createSpy()``` and we can observe basic usage of a SinonJS spy in the following example:
  3695. ####Basic Spies:
  3696. ```javascript
  3697. test("should call all subscribers for a message exactly once", function () {
  3698. var message = getUniqueString();
  3699. var spy = this.spy();
  3700. PubSub.subscribe( message, spy );
  3701. PubSub.publishSync( message, "Hello World" );
  3702. ok( spy1.calledOnce, "the subscriber was called once" );
  3703. });
  3704. ```
  3705. We can also use ```this.spy()``` to spy on existing functions (like jQuery's ```$.ajax```) in the example below. When spying on a function which already exists, the function behaves normally but we get access to data about its calls which can be very useful for testing purposes.
  3706. ####Spying On Existing Functions:
  3707. ```javascript
  3708. test( "should inspect jQuery.getJSON's usage of jQuery.ajax", function () {
  3709. this.spy( jQuery, "ajax" );
  3710. jQuery.getJSON( "/todos/completed" );
  3711. ok( jQuery.ajax.calledOnce );
  3712. equals( jQuery.ajax.getCall(0).args[0].url, "/todos/completed" );
  3713. equals( jQuery.ajax.getCall(0).args[0].dataType, "json" );
  3714. });
  3715. ```
  3716. SinonJS comes with a rich spy interface which allows us to test whether a spy was called with a specific argument, if it was called a specific number of times and test against the values of arguments. A complete list of features supported in the interface can be found here (http://sinonjs.org/docs/), but let's take a look at some examples demonstrating some of the most commonly used ones:
  3717. ####Matching arguments: test a spy was called with a specific set of arguments:
  3718. ```javascript
  3719. test( "Should call a subscriber with standard matching": function () {
  3720. var spy = sinon.spy();
  3721. PubSub.subscribe( "message", spy );
  3722. PubSub.publishSync( "message", { id: 45 } );
  3723. assertTrue( spy.calledWith( { id: 45 } ) );
  3724. });
  3725. ```
  3726. ####Stricter argument matching: test a spy was called at least once with specific arguments and no others:
  3727. ```javascript
  3728. test( "Should call a subscriber with strict matching": function () {
  3729. var spy = sinon.spy();
  3730. PubSub.subscribe( "message", spy );
  3731. PubSub.publishSync( "message", "many", "arguments" );
  3732. PubSub.publishSync( "message", 12, 34 );
  3733. // This passes
  3734. assertTrue( spy.calledWith("many") );
  3735. // This however, fails
  3736. assertTrue( spy.calledWithExactly( "many" ) );
  3737. });
  3738. ```
  3739. ####Testing call order: testing if a spy was called before or after another spy:
  3740. ```javascript
  3741. test( "Should call a subscriber and maintain call order": function () {
  3742. var a = sinon.spy();
  3743. var b = sinon.spy();
  3744. PubSub.subscribe( "message", a );
  3745. PubSub.subscribe( "event", b );
  3746. PubSub.publishSync( "message", { id: 45 } );
  3747. PubSub.publishSync( "event", [1, 2, 3] );
  3748. assertTrue( a.calledBefore(b) );
  3749. assertTrue( b.calledAfter(a) );
  3750. });
  3751. ```
  3752. ####Match execution counts: test a spy was called a specific number of times:
  3753. ```javascript
  3754. test( "Should call a subscriber and check call counts", function () {
  3755. var message = getUniqueString();
  3756. var spy = this.spy();
  3757. PubSub.subscribe( message, spy );
  3758. PubSub.publishSync( message, "some payload" );
  3759. // Passes if spy was called once and only once.
  3760. ok( spy.calledOnce ); // calledTwice and calledThrice are also supported
  3761. // The number of recorded calls.
  3762. equal( spy.callCount, 1 );
  3763. // Directly checking the arguments of the call
  3764. equals( spy.getCall(0).args[0], message );
  3765. });
  3766. ```
  3767. ##Stubs and mocks
  3768. SinonJS also supports two other powerful features which are useful to be aware of: stubs and mocks. Both stubs and mocks implement all of the features of the spy API, but have some added functionality.
  3769. ###Stubs
  3770. A stub allows us to replace any existing behaviour for a specific method with something else. They can be very useful for simulating exceptions and are most often used to write test cases when certain dependencies of your code-base may not yet be written.
  3771. Let us briefly re-explore our Backbone Todo application, which contained a Todo model and a TodoList collection. For the purpose of this walkthrough, we want to isolate our TodoList collection and fake the Todo model to test how adding new models might behave.
  3772. We can pretend that the models have yet to be written just to demonstrate how stubbing might be carried out. A shell collection just containing a reference to the model to be used might look like this:
  3773. ```javascript
  3774. var TodoList = Backbone.Collection.extend({
  3775. model: Todo
  3776. });
  3777. // Let's assume our instance of this collection is
  3778. this.todoList;
  3779. ```
  3780. Assuming our collection is instantiating new models itself, it's necessary for us to stub the models constructor function for the the test. This can be done by creating a simple stub as follows:
  3781. ```javascript
  3782. this.todoStub = sinon.stub( window, "Todo" );
  3783. ```
  3784. The above creates a stub of the Todo method on the window object. When stubbing a persistent object, it's necessary to restore it to its original state. This can be done in a ```teardown()``` as follows:
  3785. ```javascript
  3786. this.todoStub.restore();
  3787. ```
  3788. After this, we need to alter what the constructor returns, which can be efficiently done using a plain ```Backbone.Model``` constructor. Whilst this isn't a Todo model, it does still provide us an actual Backbone model.
  3789. ```javascript
  3790. teardown: function() {
  3791. this.todoStub = sinon.stub( window, "Todo" );
  3792. this.model = new Backbone.Model({
  3793. id: 2,
  3794. title: "Hello world"
  3795. });
  3796. this.todoStub.returns( this.model );
  3797. });
  3798. ```
  3799. The expectation here might be that this snippet would ensure our TodoList collection always instantiates a stubbed Todo model, but because a reference to the model in the collection is already present, we need to reset the model property of our collection as follows:
  3800. ```javascript
  3801. this.todoList.model = Todo;
  3802. ```
  3803. The result of this is that when our TodoList collection instantiates new Todo models, it will return our plain Backbone model instance as desired. This allows us to write a spec for testing the addition of new model literals as follows:
  3804. ```javascript
  3805. module( "Should function when instantiated with model literals", {
  3806. setup:function() {
  3807. this.todoStub = sinon.stub(window, "Todo");
  3808. this.model = new Backbone.Model({
  3809. id: 2,
  3810. title: "Hello world"
  3811. });
  3812. this.todoStub.returns(this.model);
  3813. this.todos = new TodoList();
  3814. // Let's reset the relationship to use a stub
  3815. this.todos.model = Todo;
  3816. this.todos.add({
  3817. id: 2,
  3818. title: "Hello world"
  3819. });
  3820. },
  3821. teardown: function() {
  3822. this.todoStub.restore();
  3823. }
  3824. });
  3825. test("should add a model", function() {
  3826. equal( this.todos.length, 1 );
  3827. });
  3828. test("should find a model by id", function() {
  3829. equal( this.todos.get(5).get("id"), 5 );
  3830. });
  3831. });
  3832. ```
  3833. ###Mocks
  3834. Mocks are effectively the same as stubs, however they mock a complete API out and have some built-in expectations for how they should be used. The difference between a mock and a spy is that as the expectations for their use are pre-defined, it will fail if any of these are not met.
  3835. Here's a snippet with sample usage of a mock based on PubSubJS. Here, we have a `clearTodo()` method as a callback and use mocks to verify its behavior.
  3836. ```javascript
  3837. test("should call all subscribers when exceptions", function () {
  3838. var myAPI = { clearTodo: function () {} };
  3839. var spy = this.spy();
  3840. var mock = this.mock( myAPI );
  3841. mock.expects( "clearTodo" ).once().throws();
  3842. PubSub.subscribe( "message", myAPI.clearTodo );
  3843. PubSub.subscribe( "message", spy );
  3844. PubSub.publishSync( "message", undefined );
  3845. mock.verify();
  3846. ok( spy.calledOnce );
  3847. });
  3848. ```
  3849. Practical
  3850. ====================
  3851. We can now begin writing test specs for our Todo application, which are listed and separated by component (e.g Models, Collections etc.). It's useful to pay attention to the name of the test, the logic being tested and most importantly the assertions being made as this will give you some insight into how what we've learned can be applied to a complete application.
  3852. To get the most out of this section, I recommend looking at the QUnit Koans included in the `practicals\qunit-koans` folder - this is a port of the Backbone.js Jasmine Koans over to QUnit that I converted for this post.
  3853. *In case you haven't had a chance to try out one of the Koans kits as yet, they are a set of unit tests using a specific testing framework that both demonstrate how a set of specs for an application may be written, but also leave some tests unfilled so that you can complete them as an exercise.*
  3854. ###Models
  3855. For our models we want to at minimum test that:
  3856. * New instances can be created with the expected default values
  3857. * Attributes can be set and retrieved correctly
  3858. * Changes to state correctly fire off custom events where needed
  3859. * Validation rules are correctly enforced
  3860. ```javascript
  3861. module( 'About Backbone.Model');
  3862. test('Can be created with default values for its attributes.', function() {
  3863. expect( 1 );
  3864. var todo = new Todo();
  3865. equal( todo.get('text'), "" );
  3866. });
  3867. test('Will set attributes on the model instance when created.', function() {
  3868. expect( 3 );
  3869. var todo = new Todo( { text: 'Get oil change for car.' } );
  3870. equal( todo.get('text'), "Get oil change for car." );
  3871. equal( todo.get('done'), false );
  3872. equal( todo.get('order'), 0 );
  3873. });
  3874. test('Will call a custom initialize function on the model instance when created.', function() {
  3875. expect( 1 );
  3876. var toot = new Todo({ text: 'Stop monkeys from throwing their own crap!' });
  3877. equal( toot.get('text'), 'Stop monkeys from throwing their own rainbows!' );
  3878. });
  3879. test('Fires a custom event when the state changes.', function() {
  3880. expect( 1 );
  3881. var spy = this.spy();
  3882. var todo = new Todo();
  3883. todo.on( 'change', spy );
  3884. // How would you update a property on the todo here?
  3885. // Hint: http://documentcloud.github.com/backbone/#Model-set
  3886. todo.set( { text: "new text" } );
  3887. ok( spy.calledOnce, "A change event callback was correctly triggered" );
  3888. });
  3889. test('Can contain custom validation rules, and will trigger an error event on failed validation.', function() {
  3890. expect( 3 );
  3891. var errorCallback = this.spy();
  3892. var todo = new Todo();
  3893. todo.on('error', errorCallback);
  3894. // What would you need to set on the todo properties to cause validation to fail?
  3895. todo.set( { done: "not a boolean" } );
  3896. ok( errorCallback.called, 'A failed validation correctly triggered an error' );
  3897. notEqual( errorCallback.getCall(0), undefined );
  3898. equal( errorCallback.getCall(0).args[1], 'Todo.done must be a boolean value.' );
  3899. });
  3900. ```
  3901. ###Collections
  3902. For our collection we'll want to test that:
  3903. * New model instances can be added as both objects and arrays
  3904. * Changes to models result in any necessary custom events being fired
  3905. * A `url` property for defining the URL structure for models is correctly defined
  3906. ```javascript
  3907. module( 'About Backbone.Collection');
  3908. test( 'Can add Model instances as objects and arrays.', function() {
  3909. expect( 3 );
  3910. var todos = new TodoList();
  3911. equal( todos.length, 0 );
  3912. todos.add( { text: 'Clean the kitchen' } );
  3913. equal( todos.length, 1 );
  3914. todos.add([
  3915. { text: 'Do the laundry', done: true },
  3916. { text: 'Go to the gym' }
  3917. ]);
  3918. equal( todos.length, 3 );
  3919. });
  3920. test( 'Can have a url property to define the basic url structure for all contained models.', function() {
  3921. expect( 1 );
  3922. var todos = new TodoList();
  3923. equal( todos.url, '/todos/' );
  3924. });
  3925. test('Fires custom named events when the models change.', function() {
  3926. expect(2);
  3927. var todos = new TodoList();
  3928. var addModelCallback = this.spy();
  3929. var removeModelCallback = this.spy();
  3930. todos.on( 'add', addModelCallback );
  3931. todos.on( 'remove', removeModelCallback );
  3932. // How would you get the 'add' event to trigger?
  3933. todos.add( {text:"New todo"} );
  3934. ok( addModelCallback.called );
  3935. // How would you get the 'remove' callback to trigger?
  3936. todos.remove( todos.last() );
  3937. ok( removeModelCallback.called );
  3938. });
  3939. ```
  3940. ###Views
  3941. For our views we want to ensure:
  3942. * They are being correctly tied to a DOM element when created
  3943. * They can render, after which the DOM representation of the view should be visible
  3944. * They support wiring up view methods to DOM elements
  3945. One could also take this further and test that user interactions with the view correctly result in any models that need to be changed being updated correctly.
  3946. ```javascript
  3947. module( 'About Backbone.View', {
  3948. setup: function() {
  3949. $('body').append('<ul id="todoList"></ul>');
  3950. this.todoView = new TodoView({ model: new Todo() });
  3951. },
  3952. teardown: function() {
  3953. this.todoView.remove();
  3954. $('#todoList').remove();
  3955. }
  3956. });
  3957. test('Should be tied to a DOM element when created, based off the property provided.', function() {
  3958. expect( 1 );
  3959. equal( this.todoView.el.tagName.toLowerCase(), 'li' );
  3960. });
  3961. test('Is backed by a model instance, which provides the data.', function() {
  3962. expect( 2 );
  3963. notEqual( this.todoView.model, undefined );
  3964. equal( this.todoView.model.get('done'), false );
  3965. });
  3966. test('Can render, after which the DOM representation of the view will be visible.', function() {
  3967. this.todoView.render();
  3968. // Hint: render() just builds the DOM representation of the view, but doesn't insert it into the DOM.
  3969. // How would you append it to the ul#todoList?
  3970. // How do you access the view's DOM representation?
  3971. //
  3972. // Hint: http://documentcloud.github.com/backbone/#View-el
  3973. $('ul#todoList').append(this.todoView.el);
  3974. equal($('#todoList').find('li').length, 1);
  3975. });
  3976. asyncTest('Can wire up view methods to DOM elements.', function() {
  3977. expect( 2 );
  3978. var viewElt;
  3979. $('#todoList').append( this.todoView.render().el );
  3980. setTimeout(function() {
  3981. viewElt = $('#todoList li input.check').filter(':first');
  3982. equal(viewElt.length > 0, true);
  3983. // Make sure that QUnit knows we can continue
  3984. start();
  3985. }, 1000, 'Expected DOM Elt to exist');
  3986. // Hint: How would you trigger the view, via a DOM Event, to toggle the 'done' status.
  3987. // (See todos.js line 70, where the events hash is defined.)
  3988. //
  3989. // Hint: http://api.jquery.com/click
  3990. $('#todoList li input.check').click();
  3991. expect( this.todoView.model.get('done'), true );
  3992. });
  3993. ```
  3994. ###Events
  3995. For events, we may want to test a few different use cases:
  3996. * Extending plain objects to support custom events
  3997. * Binding and triggering custom events on objects
  3998. * Passing along arguments to callbacks when events are triggered
  3999. * Binding a passed context to an event callback
  4000. * Removing custom events
  4001. and a few others that will be detailed in our module below:
  4002. ```javascript
  4003. module( 'About Backbone.Events', {
  4004. setup: function() {
  4005. this.obj = {};
  4006. _.extend( this.obj, Backbone.Events );
  4007. this.obj.off(); // remove all custom events before each spec is run.
  4008. }
  4009. });
  4010. test('Can extend JavaScript objects to support custom events.', function() {
  4011. expect(3);
  4012. var basicObject = {};
  4013. // How would you give basicObject these functions?
  4014. // Hint: http://documentcloud.github.com/backbone/#Events
  4015. _.extend( basicObject, Backbone.Events );
  4016. equal( typeof basicObject.on, 'function' );
  4017. equal( typeof basicObject.off, 'function' );
  4018. equal( typeof basicObject.trigger, 'function' );
  4019. });
  4020. test('Allows us to bind and trigger custom named events on an object.', function() {
  4021. expect( 1 );
  4022. var callback = this.spy();
  4023. this.obj.on( 'basic event', callback );
  4024. this.obj.trigger( 'basic event' );
  4025. // How would you cause the callback for this custom event to be called?
  4026. ok( callback.called );
  4027. });
  4028. test('Also passes along any arguments to the callback when an event is triggered.', function() {
  4029. expect( 1 );
  4030. var passedArgs = [];
  4031. this.obj.on('some event', function() {
  4032. for (var i = 0; i < arguments.length; i++) {
  4033. passedArgs.push( arguments[i] );
  4034. }
  4035. });
  4036. this.obj.trigger( 'some event', 'arg1', 'arg2' );
  4037. deepEqual( passedArgs, ['arg1', 'arg2'] );
  4038. });
  4039. test('Can also bind the passed context to the event callback.', function() {
  4040. expect( 1 );
  4041. var foo = { color: 'blue' };
  4042. var changeColor = function() {
  4043. this.color = 'red';
  4044. };
  4045. // How would you get 'this.color' to refer to 'foo' in the changeColor function?
  4046. this.obj.on( 'an event', changeColor, foo );
  4047. this.obj.trigger( 'an event' );
  4048. equal( foo.color, 'red' );
  4049. });
  4050. test( "Uses 'all' as a special event name to capture all events bound to the object." , function() {
  4051. expect( 2 );
  4052. var callback = this.spy();
  4053. this.obj.on( 'all', callback );
  4054. this.obj.trigger( "custom event 1" );
  4055. this.obj.trigger( "custom event 2" );
  4056. equal( callback.callCount, 2 );
  4057. equal( callback.getCall(0).args[0], 'custom event 1' );
  4058. });
  4059. test('Also can remove custom events from objects.', function() {
  4060. expect( 5 );
  4061. var spy1 = this.spy();
  4062. var spy2 = this.spy();
  4063. var spy3 = this.spy();
  4064. this.obj.on( 'foo', spy1 );
  4065. this.obj.on( 'bar', spy1 );
  4066. this.obj.on( 'foo', spy2 );
  4067. this.obj.on( 'foo', spy3 );
  4068. // How do you unbind just a single callback for the event?
  4069. this.obj.off( 'foo', spy1 );
  4070. this.obj.trigger( 'foo' );
  4071. ok( spy2.called );
  4072. // How do you unbind all callbacks tied to the event with a single method
  4073. this.obj.off( 'foo' );
  4074. this.obj.trigger( 'foo' );
  4075. ok( spy2.callCount, 1 );
  4076. ok( spy2.calledOnce, "Spy 2 called once" );
  4077. ok( spy3.calledOnce, "Spy 3 called once" );
  4078. // How do you unbind all callbacks and events tied to the object with a single method?
  4079. this.obj.off( 'bar' );
  4080. this.obj.trigger( 'bar' );
  4081. equal( spy1.callCount, 0 );
  4082. });
  4083. ```
  4084. ###App
  4085. It can also be useful to write specs for any application bootstrap you may have in place. For the following module, our setup initiates and appends a TodoApp view and we can test anything from local instances of views being correctly defined to application interactions correctly resulting in changes to instances of local collections.
  4086. ```javascript
  4087. module( 'About Backbone Applications' , {
  4088. setup: function() {
  4089. Backbone.localStorageDB = new Store('testTodos');
  4090. $('#qunit-fixture').append('<div id="app"></div>');
  4091. this.App = new TodoApp({ appendTo: $('#app') });
  4092. },
  4093. teardown: function() {
  4094. this.App.todos.reset();
  4095. $('#app').remove();
  4096. }
  4097. });
  4098. test('Should bootstrap the application by initializing the Collection.', function() {
  4099. expect( 2 );
  4100. notEqual( this.App.todos, undefined );
  4101. equal( this.App.todos.length, 0 );
  4102. });
  4103. test( 'Should bind Collection events to View creation.' , function() {
  4104. $('#new-todo').val( 'Foo' );
  4105. $('#new-todo').trigger(new $.Event( 'keypress', { keyCode: 13 } ));
  4106. equal( this.App.todos.length, 1 );
  4107. });
  4108. ```
  4109. ##Further Reading & Resources
  4110. That's it for this section on testing applications with QUnit and SinonJS. I encourage you to try out the [QUnit Backbone.js Koans](https://github.com/addyosmani/backbone-koans-qunit) and see if you can extend some of the examples. For further reading consider looking at some of the additional resources below:
  4111. * **[Test-driven JavaScript Development (book)](http://tddjs.com/)**
  4112. * **[SinonJS/QUnit Adapter](http://sinonjs.org/qunit/)**
  4113. * **[SinonJS and QUnit](http://cjohansen.no/en/javascript/using_sinon_js_with_qunit)**
  4114. * **[Automating JavaScript Testing With QUnit](http://msdn.microsoft.com/en-us/scriptjunkie/gg749824)**
  4115. * **[Ben Alman's Unit Testing With QUnit](http://benalman.com/talks/unit-testing-qunit.html)**
  4116. * **[Another QUnit/Backbone.js demo project](https://github.com/jc00ke/qunit-backbone)**
  4117. * **[SinonJS helpers for Backbone](http://devblog.supportbee.com/2012/02/10/helpers-for-testing-backbone-js-apps-using-jasmine-and-sinon-js/)**
  4118. <a name="resources">Resources</a>
  4119. ---
  4120. Whilst we get with Backbone out of the box can be terribly useful, there are some equally beneficial add-ons that can help simplify our development process. These include:
  4121. * [Backbone Layout Manager](https://github.com/tbranyen/backbone.layoutmanager)
  4122. * [Backbone Boilerplate](https://github.com/backbone-boilerplate/backbone-boilerplate)
  4123. * [Backbone Model Binding](https://github.com/derickbailey/backbone.modelbinding)
  4124. * [Backbone Relational - for model relationships](https://github.com/PaulUithol/Backbone-relational)
  4125. * [View and model inheritance](https://gist.github.com/1271041)
  4126. * [Backbone Marionette](https://github.com/derickbailey/backbone.marionette)
  4127. * [Backbone CouchDB](https://github.com/janmonschke/backbone-couchdb)
  4128. * [Backbone Validations - HTML5 inspired validations](https://github.com/n-time/backbone.validations)
  4129. In time, there will be tutorials in the book covering some of these resources but until then, please feel free to check them out.
  4130. <a name="conclusions">Conclusions</a>
  4131. ---
  4132. That's it for 'Developing Backbone.js Applications'. I hope you found this book both useful, enlightening and a good start for your journey into exploring Backbone.js.
  4133. Remember, If there are other topics or areas of this book you feel could be expanded further, please feel free to let me know, or better yet, send a pull request upstream. I'm always interested in making this title as comprehensive as possible.
  4134. Until next time, the very best of luck with the rest of your journey!
  4135. ---
  4136. Copyright Addy Osmani, 2012.