Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
4320 lines (3804 sloc) 438 KB
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<title>Developing Backbone.js Applications - </title>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > { color: #40a070; }
code > span.fl { color: #40a070; }
code > { color: #4070a0; }
code > { color: #4070a0; }
code > { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > { color: #ff0000; font-weight: bold; }
<link rel="stylesheet" href="style.css" type="text/css" />
<h1>Developing Backbone.js Applications</h1>
<h3>By Addy Osmani <a href="">@addyosmani</a></h3>
<div style="width:500px">
<iframe src=";repo=backbone-fundamentals&amp;type=watch&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<iframe allowtransparency="true" frameborder="0" scrolling="no" src=";count=horizontal&amp;id=twitter-widget-0&amp;lang=en&amp;;size=m&amp;text=Developing%20Backbone.js%20Applications&amp;;via=addy_osmani" class="twitter-share-button twitter-count-horizontal" style="width: 107px; height: 20px; " title="Twitter Tweet Button"></iframe>
<script id="twitter-wjs" src="//"></script><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);;js.src="//";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<h2 id="prelude">Prelude</h2>
<p>Welcome to my (in-progress) book about the <a href="">Backbone.js</a> framework for structuring JavaScript applications. It's released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported <a href="">license</a> meaning you can both grab a copy of the book for free or help to further <a href="">improve</a> it.</p>
<p>I'm very pleased to announce that this book will be out in physical form in a few months time via <a href="">O'Reilly Media</a>. 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.</p>
<p>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. My extended thanks go out to <a href="">Jeremy Ashkenas</a> for creating Backbone.js and <a href="">these</a> members of the community for their assistance tweaking this project.</p>
<p>I hope you find this book helpful!</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<li><h4><a href="#introduction">Introduction</a></h4></li>
<li><h4><a href="#fundamentals">Fundamentals</a></h4>
<li><a href="#mvc-mvp">MVC, MVP &amp; Backbone.js</a></li>
<li><h4><a href="#thebasics">The Basics</a></h4>
<li><a href="#models">Models</a></li>
<li><a href="#views">Views</a></li>
<li><a href="#collections">Collections</a></li>
<li><a href="#routers">Routers</a></li>
<li><a href="#namespacing">Namespacing</a></li>
<li><a href="#additional-tips">Additional tips</a></li>
<li><h4><a href="#restfulapps">RESTful Applications</a></h4>
<li><a href="#restful">Building RESTful applications with Backbone</a></li>
<li><a href="#stack1">Building Backbone apps with Node.js, Express, Mongoose and MongoDB</a></li>
<li><a href="#stack2">Building Backbone apps with Ruby, Sinatra, Haml and MongoDB</a></li>
<li><a href="#pagination">Paginating Backbone.js Requests &amp; Collections</a></li>
<li><h4><a href="#advanced">Advanced</a></h4>
<li><a href="#modularjs">Modular JavaScript</a></li>
<li><a href="#organizingmodules">Organizing modules with RequireJS and AMD</a></li>
<li><a href="#externaltemplates">Keeping your templates external with the RequireJS text plugin</a></li>
<li><a href="#optimizingrequirejs">Optimizing Backbone apps for production with the RequireJS Optimizer</a></li>
<li><a href="#practicalrequirejs">Practical: Building a modular Backbone app with AMD &amp; RequireJS</a></li>
<li><a href="#decouplingbackbone">Decoupling Backbone with the Mediator and Facade patterns</a></li>
<li>Backbone &amp; jQuery Mobile</li>
<li>Practical: Building A Modular Mobile App With Backbone &amp; jQuery Mobile</li>
<li><h4><a href="#testing">Unit Testing</a></h4>
<li><a href="#unittestingjasmine">Unit Testing Backbone Applications With Jasmine</a></li>
<li>Suites, Specs And Spies</li>
<li>TDD With Backbone</li>
<li><a href="#testing-jasmine-models">Testing Models</a></li>
<li><a href="#testing-jasmine-collections">Testing Collections</a></li>
<li><a href="#testing-jasmine-views">Testing Views</a></li>
<li><a href="#unittestingqunit">Unit Testing Backbone Applications With QUnit And SinonJS</a></li>
<li>Adding structure to assertions</li>
<li>Assertion examples</li>
<li>Asynchronous code</li>
<li>Testing Models</li>
<li>Testing Collections</li>
<li>Testing Views</li>
<li>Testing Events</li>
<li><h4><a href="#resources">Resources</a></h4></li>
<h2 id="introduction"><a name="introduction">Introduction</a></h2>
<p>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.</p>
<p>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?</p>
<p>In this book, I will be covering the popular Backbone.js, which I consider the best of the current family of JavaScript architectural frameworks.</p>
<p>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.</p>
<p>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 href="">a Todo application</a> can be implemented in Backbone and several other popular Javascript frameworks before reading further?</p>
<p>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.</p>
<h2 id="fundamentals"><a name="fundamentals">Fundamentals</a></h2>
<p>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.</p>
<h3 id="mvc-mvp-backbone.js"><a name="mvc-mvp">MVC, MVP &amp; Backbone.js</a></h3>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<h2 id="mvc">MVC</h2>
<p>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 <a href="">Trygve Reenskaug</a> while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in <a href="">“Design Patterns: Elements of Reusable Object-Oriented Software”</a> (The &quot;GoF&quot; or “Gang of Four” book) in 1994, which played a role in popularizing its use.</p>
<h3 id="smalltalk-80-mvc">Smalltalk-80 MVC</h3>
<p>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 <a href="">Separated Presentation</a> 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.</p>
<p>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:</p>
<li>A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers)</li>
<li>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</li>
<li>The Controller's role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.</li>
<li>The Observer pattern was relied upon for updating the View whenever the Model changed</li>
<p>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.</p>
<p>Martin Fowler has done an excellent job of writing about the <a href="">origins</a> of MVC over the years and if you are interested in further historical information about Smalltalk-80's MVC, I recommend reading his work.</p>
<h2 id="mvc-as-we-know-it">MVC As We Know It</h2>
<p>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 &quot;spaghetti&quot; 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.</p>
<p>MVC is composed of three core components:</p>
<h3 id="models">Models</h3>
<p>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.</p>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default attributes for the photo</span>
<span class="dt">defaults</span>: {
<span class="co">// Ensure that each photo created has an `src`.</span>
<span class="dt">src</span>: <span class="st">&quot;placeholder.jpg&quot;</span>,
<span class="dt">caption</span>: <span class="st">&quot;A default image&quot;</span>,
<span class="dt">viewed</span>: <span class="kw">false</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<p>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.</p>
<p>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.</p>
<p>It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called &quot;Collections&quot;. 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.</p>
<p>Here's how we might group Photo models into a simplified Backbone Collection:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoGallery = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="co">// Reference to this collection&#39;s model.</span>
<span class="dt">model</span>: Photo,
<span class="co">// Filter down the list of all photos that have been viewed</span>
<span class="dt">viewed</span>: <span class="kw">function</span>() {
<span class="kw">return</span> <span class="kw">this</span>.<span class="fu">filter</span>(<span class="kw">function</span>(photo){ <span class="kw">return</span> <span class="kw">photo</span>.<span class="fu">get</span>(<span class="ch">&#39;viewed&#39;</span>); });
<span class="co">// Filter down the list to only photos that have not yet been viewed</span>
<span class="dt">unviewed</span>: <span class="kw">function</span>() {
<span class="kw">return</span> <span class="kw">this</span>.<span class="fu">without</span>.<span class="fu">apply</span>(<span class="kw">this</span>, <span class="kw">this</span>.<span class="fu">viewed</span>());
<p>If you read older texts on MVC, you may come across a description of models as also managing application 'state'. In JavaScript applications &quot;state&quot; has a specific meaning, typically referring to the current &quot;state&quot; 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.</p>
<h3 id="views">Views</h3>
<p>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.</p>
<p>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 &quot;edit&quot; view where a user who has selected a specific photo could edit its caption, tags, or other metadata in a form.</p>
<p>In MVC, the actual task of updating the Model falls to Controllers, which we'll be covering shortly.</p>
<p>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.</p>
<p>We define a <code>render()</code> utility within our view which is responsible for rendering the contents of the <code>photoModel</code> using a JavaScript templating engine (Underscore templating) and updating the contents of our view, referenced by <code>photoEl</code>.</p>
<p>The <code>photoModel</code> then adds our <code>render()</code> callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes.</p>
<p>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 <code>photoEl</code> which will delegate handling the click behavior back to the controller, passing the model information along with it in case it's needed.</p>
<p>The benefit of this architecture is that each component plays its own separate role in making the application function as needed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> buildPhotoView = <span class="kw">function</span>( photoModel, photoController ){
<span class="kw">var</span> base = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>),
photoEl = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>);
<span class="kw">base</span>.<span class="fu">appendChild</span>(photoEl);
<span class="kw">var</span> render= <span class="kw">function</span>(){
<span class="co">// We use a templating library such as Underscore</span>
<span class="co">// templating which generates the HTML for our </span>
<span class="co">// photo entry</span>
<span class="kw">photoEl</span>.<span class="fu">innerHTML</span> = <span class="kw">_</span>.<span class="fu">template</span>(<span class="ch">&#39;photoTemplate&#39;</span>, {<span class="dt">src</span>: <span class="kw">photoModel</span>.<span class="fu">getSrc</span>()});
<span class="kw">photoModel</span>.<span class="fu">addSubscriber</span>( render );
<span class="kw">photoEl</span>.<span class="fu">addEventListener</span>(<span class="ch">&#39;click&#39;</span>, <span class="kw">function</span>(){
<span class="kw">photoController</span>.<span class="fu">handleEvent</span>(<span class="ch">&#39;click&#39;</span>, photoModel );
<span class="kw">var</span> show = <span class="kw">function</span>(){
<span class="kw"></span>.<span class="fu">display</span> = <span class="ch">&#39;&#39;</span>;
<span class="kw">var</span> hide = <span class="kw">function</span>(){
<span class="kw"></span>.<span class="fu">display</span> = <span class="ch">&#39;none&#39;</span>;
<span class="kw">return</span>{
<span class="dt">showView</span>: show,
<span class="dt">hideView</span>: hide
<p>In the context of JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views.</p>
<p>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 <code>document.write</code> 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.</p>
<p>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 deliminated 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.</p>
<p>Let's compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore's 'microtemplates'.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li</span><span class="ot"> class=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;h2&gt;</span>{{caption}}<span class="kw">&lt;/h2&gt;</span>
<span class="kw">&lt;img</span><span class="ot"> class=</span><span class="st">&quot;source&quot;</span><span class="ot"> src=</span><span class="st">&quot;{{src}}&quot;</span><span class="kw">/&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;meta-data&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/li&gt;</span></code></pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li</span><span class="ot"> class=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;h2&gt;</span><span class="er">&lt;</span>%= caption %&gt;<span class="kw">&lt;/h2&gt;</span>
<span class="kw">&lt;img</span><span class="ot"> class=</span><span class="st">&quot;source&quot;</span><span class="ot"> src=</span><span class="st">&quot;</span><span class="er">&lt;</span><span class="st">%= src %&gt;&quot;</span><span class="kw">/&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;meta-data&quot;</span><span class="kw">&gt;</span>
<span class="er">&lt;</span>%= metadata %&gt;
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/li&gt;</span></code></pre>
<p>You may also use double curly brackets (i.e <code>{{}}</code>) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore <code>templateSettings</code> attribute as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">_</span>.<span class="fu">templateSettings</span> = { <span class="dt">interpolate </span>: <span class="ot">/</span><span class="fl">\{\{(</span><span class="ot">.</span><span class="fl">+?)\}\}</span><span class="ot">/g</span> };</code></pre>
<p><strong>A note on navigation and state</strong></p>
<p>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 &quot;router&quot;, 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.</p>
<h3 id="controllers">Controllers</h3>
<p>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.</p>
<p>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.</p>
<p>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 &quot;proper&quot; role of controllers in other non-Javascript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone's Views typically contain &quot;controller&quot; logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC.</p>
<p>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.</p>
<h3 id="controllers-in-spine.js-vs-backbone.js">Controllers in Spine.js vs Backbone.js</h3>
<p>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 <strong>own</strong> 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 <a href="">Spine.js</a>:</p>
<p>In this example, we're going to have a controller called <code>PhotosController</code> 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.</p>
<p>(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.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Controllers in Spine are created by inheriting from Spine.Controller</span>
<span class="kw">var</span> PhotosController = <span class="kw">Spine.Controller</span>.<span class="fu">sub</span>({
<span class="dt">init</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="st">&quot;update&quot;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">render</span>));
<span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="st">&quot;destroy&quot;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">remove</span>));
<span class="dt">render</span>: <span class="kw">function</span>(){
<span class="co">// Handle templating</span>
<span class="kw">this</span>.<span class="fu">replace</span>($(<span class="st">&quot;#photoTemplate&quot;</span>).<span class="fu">tmpl</span>(<span class="kw">this</span>.<span class="fu">item</span>));
<span class="kw">return</span> <span class="kw">this</span>;
<span class="dt">remove</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.<span class="fu">el</span>.<span class="fu">remove</span>();
<span class="kw">this</span>.<span class="fu">release</span>();
<p>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).</p>
<p>What we're doing in the above example is setting up listeners in the <code>update</code> and <code>destroy</code> events using <code>render()</code> and <code>remove()</code>. 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 <code>tmpl()</code> function in the code snippet: in the <code>render()</code> 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.</p>
<p>What this provides us with is a very lightweight, simple way to manage changes between the model and the view.</p>
<p>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.</p>
<p>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.</p>
<p>A Router's main purpose is to translate URL requests into application states. When a user browses to the URL, 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 <em>can</em> 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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="dt">routes</span>: { <span class="st">&quot;photos/:id&quot;</span>: <span class="st">&quot;route&quot;</span> },
<span class="dt">route</span>: <span class="kw">function</span>(id) {
<span class="kw">var</span> item = <span class="kw">photoCollection</span>.<span class="fu">get</span>(id);
<span class="kw">var</span> view = <span class="kw">new</span> PhotoView({ <span class="dt">model</span>: item });
<span class="kw">something</span>.<span class="fu">html</span>( <span class="kw">view</span>.<span class="fu">render</span>().<span class="fu">el</span> );
<h2 id="what-does-mvc-give-us">What does MVC give us?</h2>
<p>To summarize, the separation of concerns in MVC facilitates modularization of an application's functionality and enables:</p>
<li>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.<br /></li>
<li>Decoupling models and views means that it's straight-forward to write unit tests for business logic<br /></li>
<li>Duplication of low-level model and controller code is eliminated across the application</li>
<li>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</li>
<h3 id="delving-deeper">Delving deeper</h3>
<p>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.</p>
<p>The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a &quot;set of classes to build a user interface&quot;. 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.</p>
<p>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 &quot;publishes&quot; to the rest of the application that it has been updated. The &quot;subscriber&quot;--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.</p>
<p>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.</p>
<h3 id="summary">Summary</h3>
<p>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.</p>
<p>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.</p>
<h2 id="mvp">MVP</h2>
<p>Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named <a href="">Taligent</a> 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.</p>
<p>For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.</p>
<h3 id="models-views-presenters">Models, Views &amp; Presenters</h3>
<p>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.</p>
<p>The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes &quot;dumb&quot;), 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.</p>
<p>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.</p>
<p>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.</p>
<p>Although a common implementation of a <a href="">Passive View</a> 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.</p>
<p>There is also a <a href="">Supervising Controller</a> variation of MVP, which is closer to the MVC and <a href="">MVVM</a> 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.</p>
<h2 id="mvp-or-mvc">MVP or MVC?</h2>
<p>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.</p>
<p>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.</p>
<p>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,</p>
<p>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.</p>
<h2 id="mvc-mvp-and-backbone.js">MVC, MVP and Backbone.js</h2>
<p>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 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.</p>
<p>Backbone contributor <a href="">Irene Ros</a> 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 <code>Backbone.Router</code>, covered later in the book) or a callback in response to data being fetched.</p>
<p>That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that:</p>
<li>The presenter in MVP better describes the <code>Backbone.View</code> (the layer between View templates and the data bound to it) than a controller does</li>
<li>The model fits <code>Backbone.Model</code> (it isn't that different from the classical MVC &quot;Model&quot;)<br /></li>
<li>The views best represent templates (e.g Handlebars/Mustache markup templates)</li>
<p>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 <code>Backbone.View</code> because they're able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.</p>
<p>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.</p>
<p>Here, our Backbone <code>PhotoView</code> uses the Observer pattern to 'subscribe' to changes to a View's model in the line <code>this.model.bind('change',...)</code>. It also handles templating in the <code>render()</code> method, but unlike some other implementations, user interaction is also handled in the View (see <code>events</code>).</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="co">//... is a list tag.</span>
<span class="dt">tagName</span>: <span class="st">&quot;li&quot;</span>,
<span class="co">// Pass the contents of the photo template through a templating</span>
<span class="co">// function, cache it for a single photo</span>
<span class="dt">template</span>: <span class="kw">_</span>.<span class="fu">template</span>($(<span class="ch">&#39;#photo-template&#39;</span>).<span class="fu">html</span>()),
<span class="co">// The DOM events specific to an item.</span>
<span class="dt">events</span>: {
<span class="st">&quot;click img&quot;</span> : <span class="st">&quot;toggleViewed&quot;</span>
<span class="co">// The PhotoView listens for changes to its model, re-rendering. Since there&#39;s</span>
<span class="co">// a one-to-one correspondence between a **Photo** and a **PhotoView** in this</span>
<span class="co">// app, we set a direct reference on the model for convenience.</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="kw">_</span>.<span class="fu">bindAll</span>(<span class="kw">this</span>, <span class="ch">&#39;render&#39;</span>);
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">bind</span>(<span class="ch">&#39;change&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>);
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">bind</span>(<span class="ch">&#39;destroy&#39;</span>, <span class="kw">this</span>.<span class="fu">remove</span>);
<span class="co">// Re-render the photo entry</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
$(<span class="kw">this</span>.<span class="fu">el</span>).<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">template</span>(<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>()));
<span class="kw">return</span> <span class="kw">this</span>;
<span class="co">// Toggle the `&quot;viewed&quot;` state of the model.</span>
<span class="dt">toggleViewed</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">viewed</span>();
<p>Another (quite different) opinion is that Backbone more closely resembles <a href="">Smalltalk-80 MVC</a>, which we went through earlier.</p>
<p>As regular Backbone user Derick Bailey has <a href="">written</a>, 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 <strong>the Backbone way</strong>, MV* or whatever helps reference its flavor of application architecture.</p>
<p>It <em>is</em> 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.</p>
<h2 id="fast-facts">Fast facts</h2>
<h3 id="backbone.js">Backbone.js</h3>
<li>Core components: Model, View, Collection, Router. Enforces its own flavor of MV*</li>
<li>Good documentation, with more improvements on the way</li>
<li>Used by large companies such as SoundCloud and Foursquare to build non-trivial applications</li>
<li>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</li>
<li>Supports data bindings through manual events or a separate Key-value observing (KVO) library</li>
<li>Great support for RESTful interfaces out of the box, so models can be easily tied to a backend</li>
<li>Extensive eventing system. It's <a href="">trivial</a> to add support for pub/sub in Backbone</li>
<li>Prototypes are instantiated with the <code>new</code> keyword, which some developers prefer</li>
<li>Agnostic about templating frameworks, however Underscore's micro-templating is available by default. Backbone works well with libraries like Handlebars</li>
<li>Doesn't support deeply nested models, though there are Backbone plugins such as <a href="">this</a> which can help<br /></li>
<li>Clear and flexible conventions for structuring applications. Backbone doesn't force usage of all of its components and can work with only those needed.</li>
<h2 id="the-basics">## <a name="thebasics">The Basics</a></h2>
<h3 id="what-is-backbone">What is Backbone?</h3>
<p>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.</p>
<p>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.</p>
<h3 id="why-should-you-consider-using-it">Why should you consider using it?</h3>
<p>Backbone's main benefits, regardless of your target platform or device, include helping:</p>
<li>Organize the structure to your application</li>
<li>Simplify server-side persistence</li>
<li>Decouple the DOM from your page's data</li>
<li>Model data, views and routers in a succinct manner</li>
<li>Provide DOM, model and collection synchronization</li>
<h2 id="the-basics-1">The Basics</h2>
<p>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.</p>
<h3 id="models-1"><a name="models">Models</a></h3>
<p>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.</p>
<p>Models can be created by extending <code>Backbone.Model</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>,
<span class="dt">title</span>: <span class="ch">&#39;an image placeholder&#39;</span>,
<span class="dt">coordinates</span>: [<span class="dv">0</span>,<span class="dv">0</span>]
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.<span class="fu">bind</span>(<span class="st">&quot;change:src&quot;</span>, <span class="kw">function</span>(){
<span class="kw">var</span> src = <span class="kw">this</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Image source updated to &#39;</span> + src);
<span class="dt">changeSrc</span>: <span class="kw">function</span>( source ){
<span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">src</span>: source });
<span class="kw">var</span> somePhoto = <span class="kw">new</span> Photo({ <span class="dt">src</span>: <span class="st">&quot;test.jpg&quot;</span>, <span class="dt">title</span>:<span class="st">&quot;testing&quot;</span>});
<span class="kw">somePhoto</span>.<span class="fu">changeSrc</span>(<span class="st">&quot;magic.jpg&quot;</span>); <span class="co">// which triggers &quot;change:src&quot; and logs an update message to the console.</span></code></pre>
<h4 id="initialization">Initialization</h4>
<p>The <code>initialize()</code> 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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
<span class="co">// We can then create our own instance of a photo as follows:</span>
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo();</code></pre>
<h4 id="getters-setters">Getters &amp; Setters</h4>
<p><code>Model.get()</code> provides easy access to a model's attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>: <span class="st">&quot;My awesome photo&quot;</span>,
<span class="dt">src</span>:<span class="st">&quot;boston.jpg&quot;</span>,
<span class="dt">location</span>: <span class="st">&quot;Boston&quot;</span>,
<span class="dt">tags</span>:[<span class="ch">&#39;the big game&#39;</span>, <span class="ch">&#39;vacation&#39;</span>]}),
title = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>), <span class="co">//My awesome photo</span>
location = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;location&quot;</span>), <span class="co">//Boston</span>
tags = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;tags&quot;</span>), <span class="co">// [&#39;the big game&#39;,&#39;vacation&#39;]</span>
photoSrc = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>); <span class="co">//boston.jpg</span></code></pre>
<p>Alternatively, if you wish to directly access all of the attributes in a model's instance directly, you can achieve this as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myAttributes = <span class="kw">myPhoto</span>.<span class="fu">attributes</span>;
<span class="kw">console</span>.<span class="fu">log</span>(myAttributes);</code></pre>
<p>It is best practice to use <code>Model.set()</code> or direct instantiation to set the values of a model's attributes.</p>
<p>Accessing <code>Model.attributes</code> directly is generally discouraged. Instead, should you need to read or clone data, <code>Model.toJSON()</code> 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 <code>Model.toJSON()</code>:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myAttributes = <span class="kw">myPhoto</span>.<span class="fu">toJSON</span>();
<span class="kw">console</span>.<span class="fu">log</span>(myAttributes);
<span class="co">/* this returns { title: &quot;My awesome photo&quot;, </span>
<span class="co"> src:&quot;boston.jpg&quot;, </span>
<span class="co"> location: &quot;Boston&quot;, </span>
<span class="co"> tags:[&#39;the big game&#39;, &#39;vacation&#39;]}*/</span></code></pre>
<h4 id="model.set">Model.set()</h4>
<p><code>Model.set()</code> 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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
<span class="co">// Setting the value of attributes via instantiation</span>
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>: <span class="ch">&#39;My awesome photo&#39;</span>, <span class="dt">location</span>: <span class="ch">&#39;Boston&#39;</span> });
<span class="kw">var</span> myPhoto2 = <span class="kw">new</span> Photo();
<span class="co">// Setting the value of attributes through Model.set()</span>
<span class="kw">myPhoto2</span>.<span class="fu">set</span>({ <span class="dt">title</span>:<span class="ch">&#39;Vacation in Florida&#39;</span>, <span class="dt">location</span>: <span class="ch">&#39;Florida&#39;</span> });</code></pre>
<p><strong>Default values</strong></p>
<p>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 <code>defaults</code> in your model.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>:{
<span class="dt">title</span>: <span class="ch">&#39;Another photo!&#39;</span>,
<span class="dt">tags</span>: [<span class="ch">&#39;untagged&#39;</span>],
<span class="dt">location</span>: <span class="ch">&#39;home&#39;</span>,
<span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">location</span>: <span class="st">&quot;Boston&quot;</span>,
<span class="dt">tags</span>:[<span class="ch">&#39;the big game&#39;</span>, <span class="ch">&#39;vacation&#39;</span>]}),
title = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>), <span class="co">//Another photo!</span>
location = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;location&quot;</span>), <span class="co">//Boston</span>
tags = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;tags&quot;</span>), <span class="co">// [&#39;the big game&#39;,&#39;vacation&#39;]</span>
photoSrc = <span class="kw">myPhoto</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>); <span class="co">//placeholder.jpg</span></code></pre>
<p><strong>Listening for changes to your model</strong></p>
<p>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 <code>initialize()</code> function:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">this</span>.<span class="fu">bind</span>(<span class="ch">&#39;change&#39;</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;values for this model have changed&#39;</span>);
<p>In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>:{
<span class="dt">title</span>: <span class="ch">&#39;Another photo!&#39;</span>,
<span class="dt">tags</span>: [<span class="ch">&#39;untagged&#39;</span>],
<span class="dt">location</span>: <span class="ch">&#39;home&#39;</span>,
<span class="dt">src</span>: <span class="ch">&#39;placeholder.jpg&#39;</span>
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
<span class="kw">this</span>.<span class="fu">bind</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(){
<span class="kw">var</span> title = <span class="kw">this</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;My title has been changed to.. &quot;</span> + title);
<span class="dt">setTitle</span>: <span class="kw">function</span>(newTitle){
<span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">title</span>: newTitle });
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo({ <span class="dt">title</span>:<span class="st">&quot;Fishing at the lake&quot;</span>, <span class="dt">src</span>:<span class="st">&quot;fishing.jpg&quot;</span>});
<span class="kw">myPhoto</span>.<span class="fu">setTitle</span>(<span class="ch">&#39;Fishing at sea&#39;</span>);
<span class="co">//logs &#39;My title has been changed to.. Fishing at sea&#39;</span></code></pre>
<p>Backbone supports model validation through <code>Model.validate()</code>, which allows checking the attribute values for a model prior to them being set.</p>
<p>Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from <code>.validate()</code>. If they are invalid, a custom error can be returned instead.</p>
<p>A basic example for validation can be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Photo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">validate</span>: <span class="kw">function</span>(attribs){
<span class="kw">if</span>(<span class="kw">attribs</span>.<span class="fu">src</span> === undefined){
<span class="kw">return</span> <span class="st">&quot;Remember to set a source for your image!&quot;</span>;
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;this model has been initialized&#39;</span>);
<span class="kw">this</span>.<span class="fu">bind</span>(<span class="st">&quot;error&quot;</span>, <span class="kw">function</span>(model, error){
<span class="kw">console</span>.<span class="fu">log</span>(error);
<span class="kw">var</span> myPhoto = <span class="kw">new</span> Photo();
<span class="kw">myPhoto</span>.<span class="fu">set</span>({ <span class="dt">title</span>: <span class="st">&quot;On the beach&quot;</span> });
<span class="co">//logs Remember to set a source for your image!</span></code></pre>
<h3 id="views-1"><a name="views">Views</a></h3>
<p>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 <code>render()</code> function can be bound to a model's <code>change()</code> event, allowing the view to always be up to date without requiring a full page refresh.</p>
<h4 id="creating-new-views">Creating new views</h4>
<p>Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend <code>Backbone.View</code>. I'll explain this code in detail below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoSearch = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">el</span>: $(<span class="ch">&#39;#results&#39;</span>),
<span class="dt">render</span>: <span class="kw">function</span>( event ){
<span class="kw">var</span> compiled_template = <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="st">&quot;#results-template&quot;</span>).<span class="fu">html</span>() );
<span class="kw">this</span>.<span class="fu">el</span>.<span class="fu">html</span>( compiled_template(<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>()) );
<span class="kw">return</span> <span class="kw">this</span>; <span class="co">//recommended as this enables calls to be chained.</span>
<span class="dt">events</span>: {
<span class="st">&quot;submit #searchForm&quot;</span>: <span class="st">&quot;search&quot;</span>,
<span class="st">&quot;click .reset&quot;</span>: <span class="st">&quot;reset&quot;</span>,
<span class="st">&quot;click .advanced&quot;</span>: <span class="st">&quot;switchContext&quot;</span>
<span class="dt">search</span>: <span class="kw">function</span>( event ){
<span class="co">//executed when a form &#39;#searchForm&#39; has been submitted</span>
<span class="dt">reset</span>: <span class="kw">function</span>( event ){
<span class="co">//executed when an element with class &quot;reset&quot; has been clicked.</span>
<span class="dt">switchContext</span>: <span class="kw">function</span>( event ){
<span class="co">//executed when an element with class &quot;advanced&quot; has been clicked.</span>
<h4 id="what-is-el">What is <code>el</code>?</h4>
<p><code>el</code> 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.</p>
<p>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. If the element already exists in the page, you can set <code>el</code> as either a CSS selector that matches the element or a simple reference to the DOM element.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">el</span>: <span class="ch">&#39;#footer&#39;</span>,
<span class="co">// OR</span>
<span class="dt">el</span>: <span class="kw">document</span>.<span class="fu">getElementById</span>( <span class="ch">&#39;footer&#39;</span> )</code></pre>
<p>If you want to create a new element for you view, set any combination of the following view's properties: <code>tagName</code>, <code>id</code> and <code>className</code>. A new element will be created for you by the framework and a reference to it will be available at the <code>el</code> property.</p>
<pre><code>tagName: &#39;p&#39;, // required, but defaults to &#39;div&#39; if not set
className: &#39;container&#39;, // optional, you can assign multiple classes to this property like so &#39;container homepage&#39;
id: &#39;header&#39;, // optional</code></pre>
<p>The above code creates the <code>DOMElement</code> below but doesn't append it to the DOM.</p>
<pre><code>&lt;p id=&quot;header&quot; class=&quot;container&quot;&gt;&lt;/p&gt;</code></pre>
<p><strong>Understanding <code>render()</code></strong></p>
<p><code>render()</code> 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.</p>
<p>The <code>_.template</code> 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 <code>results-template</code> to <code>_.template()</code> to be compiled. Next, I set the html of the <code>el</code> DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.</p>
<p>Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.</p>
<p><strong>The <code>events</code> attribute</strong></p>
<p>The Backbone <code>events</code> attribute allows us to attach event listeners to either custom selectors, or directly to <code>el</code> if no selector is provided. An event takes the form <code>{&quot;eventName selector&quot;: &quot;callbackFunction&quot;}</code> and a number of event-types are supported, including <code>click</code>, <code>submit</code>, <code>mouseover</code>, <code>dblclick</code> and more.</p>
<p>What isn't instantly obvious is that under the bonnet, Backbone uses jQuery's <code>.delegate()</code> to provide instant support for event delegation but goes a little further, extending it so that <code>this</code> 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.</p>
<h3 id="collections"><a name="collections">Collections</a></h3>
<p>Collections are sets of Models and are created by extending <code>Backbone.Collection</code>.</p>
<p>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.</p>
<p>In the following example, we create a PhotoCollection that will contain our Photo models:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Photo
<p><strong>Getters and Setters</strong></p>
<p>There are a few different ways to retrieve a model from a collection. The most straight-forward is to use <code>Collection.get()</code> which accepts a single id as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> skiingEpicness = <span class="kw">PhotoCollection</span>.<span class="fu">get</span>(<span class="dv">2</span>);</code></pre>
<p>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 <code>.cid</code> property.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> mySkiingCrash = <span class="kw">PhotoCollection</span>.<span class="fu">getByCid</span>(<span class="dv">456</span>);</code></pre>
<p>Backbone Collections don't have setters as such, but do support adding new models via <code>.add()</code> and removing models via <code>.remove()</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> a = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Model</span>({ <span class="dt">title</span>: <span class="ch">&#39;my vacation&#39;</span>}),
b = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Model</span>({ <span class="dt">title</span>: <span class="ch">&#39;my holiday&#39;</span>});
<span class="kw">var</span> photoCollection = <span class="kw">new</span> PhotoCollection([a,b]);
<span class="kw">photoCollection</span>.<span class="fu">remove</span>([a,b]);</code></pre>
<p><strong>Listening for events</strong></p>
<p>As collections represent a group of items, we're also able to listen for <code>add</code> and <code>remove</code> events for when new models are added or removed from the collection. Here's an example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">PhotoCollection</span>.<span class="fu">bind</span>(<span class="st">&quot;add&quot;</span>, <span class="kw">function</span>(photo) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I liked &quot;</span> + <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>) + <span class="ch">&#39; its this one, right? &#39;</span> + <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;src&quot;</span>));
<span class="kw">PhotoCollection</span>.<span class="fu">add</span>([
{<span class="dt">title</span>: <span class="st">&quot;My trip to Bali&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;bali-trip.jpg&quot;</span>},
{<span class="dt">title</span>: <span class="st">&quot;The flight home&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;long-flight-oofta.jpg&quot;</span>},
{<span class="dt">title</span>: <span class="st">&quot;Uploading pix&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;too-many-pics.jpg&quot;</span>}
<p>In addition, we're able to bind a <code>change</code> event to listen for changes to models in the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">PhotoCollection</span>.<span class="fu">bind</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;there have been updates made to this collections titles&#39;</span>);
<p><strong>Fetching models from the server</strong></p>
<p><code>Collections.fetch()</code> 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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> PhotoCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>;
<span class="kw">PhotoCollection</span>.<span class="fu">url</span> = <span class="ch">&#39;/photos&#39;</span>;
<span class="kw">PhotoCollection</span>.<span class="fu">fetch</span>();</code></pre>
<p>Under the covers, <code>Backbone.sync</code> 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.</p>
<p>In the above example if we wanted to log an event when <code>.sync()</code> was called, we could do this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I&#39;ve been passed &quot;</span> + method + <span class="st">&quot; with &quot;</span> + <span class="kw">JSON</span>.<span class="fu">stringify</span>(model));
<p><strong>Resetting/Refreshing Collections</strong></p>
<p>Rather than adding or removing models individually, you might occasionally wish to update an entire collection at once. <code>Collection.reset()</code> allows us to replace an entire collection with new models as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">PhotoCollection</span>.<span class="fu">reset</span>([
{<span class="dt">title</span>: <span class="st">&quot;My trip to Scotland&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;scotland-trip.jpg&quot;</span>},
{<span class="dt">title</span>: <span class="st">&quot;The flight from Scotland&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;long-flight.jpg&quot;</span>},
{<span class="dt">title</span>: <span class="st">&quot;Latest snap of lock-ness&quot;</span>, <span class="dt">src</span>: <span class="st">&quot;lockness.jpg&quot;</span>}]);</code></pre>
<h3 id="underscore-utility-functions">Underscore utility functions</h3>
<p>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 <code>sortBy()</code> method can be used to sort a collection of photos based on a particular attribute.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> sortedByAlphabet = <span class="kw">PhotoCollection</span>.<span class="fu">sortBy</span>(<span class="kw">function</span> (photo) {
<span class="kw">return</span> <span class="kw">photo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>).<span class="fu">toLowerCase</span>();
<p>The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official <a href="">docs</a>.</p>
<h3 id="routers"><a name="routers">Routers</a></h3>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">http</span>:<span class="co">//</span>
<span class="dt">http</span>:<span class="co">//</span></code></pre>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="st">&quot;route&quot;</span> : <span class="st">&quot;mappedFunction&quot;</span></code></pre>
<p>Let us now define our first controller by extending <code>Backbone.Router</code>. For the purposes of this guide, we're going to continue pretending we're creating a photo gallery application that requires a GalleryRouter.</p>
<p>Note the inline comments in the code example below as they continue the rest of the lesson on routers.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> GalleryRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="co">/* define the route and function maps for this router */</span>
<span class="dt">routes</span>: {
<span class="st">&quot;about&quot;</span> : <span class="st">&quot;showAbout&quot;</span>,
<span class="co">/*Sample usage:*/</span>
<span class="st">&quot;photos/:id&quot;</span> : <span class="st">&quot;getPhoto&quot;</span>,
<span class="co">/*This is an example of using a &quot;:param&quot; variable which allows us to match </span>
<span class="co"> any of the components between two URL slashes*/</span>
<span class="co">/*Sample usage:*/</span>
<span class="st">&quot;search/:query&quot;</span> : <span class="st">&quot;searchPhotos&quot;</span>
<span class="co">/*We can also define multiple routes that are bound to the same map function,</span>
<span class="co"> in this case searchPhotos(). Note below how we&#39;re optionally passing in a </span>
<span class="co"> reference to a page number if one is supplied*/</span>
<span class="co">/*Sample usage:*/</span>
<span class="st">&quot;search/:query/p:page&quot;</span> : <span class="st">&quot;searchPhotos&quot;</span>,
<span class="co">/*As we can see, URLs may contain as many &quot;:param&quot;s as we wish*/</span>
<span class="co">/*Sample usage:*/</span>
<span class="st">&quot;photos/:id/download/*imagePath&quot;</span> : <span class="st">&quot;downloadPhoto&quot;</span>,
<span class="co">/*This is an example of using a *splat. splats are able to match any number of </span>
<span class="co"> URL components and can be combined with &quot;:param&quot;s*/</span>
<span class="co">/*Sample usage:*/</span>
<span class="co">/*If you wish to use splats for anything beyond default routing, it&#39;s probably a good </span>
<span class="co"> idea to leave them at the end of a URL otherwise you may need to apply regular</span>
<span class="co"> expression parsing on your fragment*/</span>
<span class="st">&quot;*other&quot;</span> : <span class="st">&quot;defaultRoute&quot;</span>
<span class="co">/*This is a default route that also uses a *splat. Consider the</span>
<span class="co"> default route a wildcard for URLs that are either not matched or where</span>
<span class="co"> the user has incorrectly typed in a route path manually*/</span>
<span class="co">/*Sample usage:*/</span>
<span class="dt">showAbout</span>: <span class="kw">function</span>(){
<span class="dt">getPhoto</span>: <span class="kw">function</span>(id){
<span class="co">/* </span>
<span class="co"> Note that the id matched in the above route will be passed to this function</span>
<span class="co"> */</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;You are trying to reach photo &quot;</span> + id);
<span class="dt">searchPhotos</span>: <span class="kw">function</span>(query, page){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Page number: &quot;</span> + page + <span class="st">&quot; of the results for &quot;</span> + query);
<span class="dt">downloadPhoto</span>: <span class="kw">function</span>(id, path){
<span class="dt">defaultRoute</span>: <span class="kw">function</span>(other){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Invalid. You attempted to reach:&quot;</span> + other);
<span class="co">/* Now that we have a router setup, remember to instantiate it*/</span>
<span class="kw">var</span> myGalleryRouter = <span class="kw">new</span> GalleryRouter();</code></pre>
<p>As of Backbone 0.5+, it's possible to opt-in for HTML5 pushState support via <code>window.history.pushState</code>. This permits you to define routes such as 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.</p>
<h4 id="backbone.history">Backbone.history</h4>
<p>Next, we need to initialize <code>Backbone.history</code> as it handles <code>hashchange</code> events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.</p>
<p>The <code>Backbone.history.start()</code> method will simply tell Backbone that it's OK to begin monitoring all <code>hashchange</code> events as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone.history</span>.<span class="fu">start</span>();
<span class="kw">Router</span>.<span class="fu">navigate</span>();</code></pre>
<p>As an aside, if you would like to save application state to the URL at a particular point you can use the <code>.navigate()</code> method to achieve this. It simply updates your URL fragment without the need to trigger the <code>hashchange</code> event:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/*Lets imagine we would like a specific fragment for when a user zooms into a photo*/</span>
<span class="dt">zoomPhoto</span>: <span class="kw">function</span>(factor){
<span class="kw">this</span>.<span class="fu">zoom</span>(factor); <span class="co">//imagine this zooms into the image</span>
<span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;zoom/&quot;</span> + factor); <span class="co">//updates the fragment for us, but doesn&#39;t trigger the route</span>
<p>It is also possible for <code>Router.navigate()</code> to trigger the route as well as updating the URL fragment.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">zoomPhoto</span>: <span class="kw">function</span>(factor){
<span class="kw">this</span>.<span class="fu">zoom</span>(factor); <span class="co">//imagine this zooms into the image</span>
<span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;zoom/&quot;</span> + factor, <span class="kw">true</span>); <span class="co">//updates the fragment for us and triggers the route</span>
<h3 id="namespacing"><a name="namespacing">Namespacing</a></h3>
<p>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.</p>
<h4 id="what-is-namespacing">What is namespacing?</h4>
<p>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.</p>
<p>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.</p>
<p>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:</p>
<li>Single global variables</li>
<li>Object Literals</li>
<li>Nested namespacing</li>
<p><strong>Single global variables</strong></p>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication = (<span class="kw">function</span>(){
<span class="kw">function</span>(){
<span class="co">// ...</span>
<span class="kw">return</span> {
<span class="co">// ...</span>
<p>You've probably seen this technique before. A Backbone-specific example might look like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myViews = (<span class="kw">function</span>(){
<span class="kw">return</span> {
<span class="dt">PhotoView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
<span class="dt">GalleryView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
<span class="dt">AboutView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. });
<span class="co">//etc.</span>
<p>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.</p>
<p>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, <code>myApplication_</code>) and then define any methods, variables or other objects after the prefix.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication_photoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({}),
myApplication_galleryView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});</code></pre>
<p>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.</p>
<p>For more on Peter's views about the single global variable pattern, read his <a href="">excellent post on them</a>.</p>
<p>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.</p>
<p><strong>Object Literals</strong></p>
<p>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.</p>
<p>This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/*Doesn&#39;t check for existence of myApplication*/</span>
<span class="kw">var</span> myApplication = {};
<span class="co">/*</span>
<span class="co">Does check for existence. If already defined, we use that instance.</span>
<span class="co">Option 1: if(!myApplication) myApplication = {};</span>
<span class="co">Option 2: var myApplication = myApplication || {};</span>
<span class="co">We can then populate our object literal to support models, views and collections (or any data, really):</span>
<span class="co">*/</span>
<span class="kw">var</span> myApplication = {
<span class="dt">models </span>: {},
<span class="dt">views </span>: {
<span class="dt">pages </span>: {}
<span class="dt">collections </span>: {}
<p>One can also opt for adding properties directly to the namespace (such as your views, in the following example):</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myGalleryViews = myGalleryViews || {};
<span class="kw">myGalleryViews</span>.<span class="fu">photoView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});
<span class="kw">myGalleryViews</span>.<span class="fu">galleryView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});</code></pre>
<p>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.</p>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myConfig = {
<span class="dt">language</span>: <span class="ch">&#39;english&#39;</span>,
<span class="dt">defaults</span>: {
<span class="dt">enableGeolocation</span>: <span class="kw">true</span>,
<span class="dt">enableSharing</span>: <span class="kw">false</span>,
<span class="dt">maxPhotos</span>: <span class="dv">20</span>
<span class="dt">theme</span>: {
<span class="dt">skin</span>: <span class="ch">&#39;a&#39;</span>,
<span class="dt">toolbars</span>: {
<span class="dt">index</span>: <span class="ch">&#39;ui-navigation-toolbar&#39;</span>,
<span class="dt">pages</span>: <span class="ch">&#39;ui-custom-toolbar&#39;</span>
<p>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.</p>
<p>For more on the Object Literal pattern, I recommend reading Rebecca Murphey's <a href="">excellent article on the topic</a>.</p>
<p><strong>Nested namespacing</strong></p>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">YAHOO.util.Dom</span>.<span class="fu">getElementsByClassName</span>(<span class="ch">&#39;test&#39;</span>);</code></pre>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> galleryApp = galleryApp || {};
<span class="co">// perform similar check for nested children</span>
<span class="kw">galleryApp</span>.<span class="fu">routers</span> = <span class="kw">galleryApp</span>.<span class="fu">routers</span> || {};
<span class="kw">galleryApp</span>.<span class="fu">model</span> = <span class="kw">galleryApp</span>.<span class="fu">model</span> || {};
<span class="kw">galleryApp.model</span>.<span class="fu">special</span> = <span class="kw">galleryApp.model</span>.<span class="fu">special</span> || {};
<span class="co">// routers</span>
<span class="kw">galleryApp.routers</span>.<span class="fu">Workspace</span> = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({});
<span class="kw">galleryApp.routers</span>.<span class="fu">PhotoSearch</span> = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({});
<span class="co">// models</span>
<span class="kw">galleryApp.model</span>.<span class="fu">Photo</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});
<span class="kw">galleryApp.model</span>.<span class="fu">Comment</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});
<span class="co">// special models</span>
<span class="kw">galleryApp.model.special</span>.<span class="fu">Admin</span> = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});</code></pre>
<p>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.</p>
<p>Reviewing the namespace patterns above, the option that I prefer when writing Backbone applications is nested object namespacing with the object literal pattern.</p>
<p>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.</p>
<h3 id="additional-tips"><a name="additional-tips">Additional Tips</a></h3>
<h4 id="automated-backbone-scaffolding">Automated Backbone Scaffolding</h4>
<p>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 <a href="">Brunch</a>.</p>
<p>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.</p>
<p>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.</p>
<h4 id="is-there-a-limit-to-the-number-of-routers-i-should-be-using">Is there a limit to the number of routers I should be using?</h4>
<p>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.</p>
<h4 id="is-backbone-too-small-for-my-applications-needs">Is Backbone too small for my application's needs?</h4>
<p>If you find yourself unsure of whether or not your application is too large to use Backbone, I recommend reading my post on building large-scale jQuery &amp; 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.</p>
<p>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.</p>
<p>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.</p>
<h2 id="restful-applications">## <a name="restfulapps">RESTful Applications</a></h2>
<h2 id="building-restful-applications-with-backbone"><a name="restful">Building RESTful applications with Backbone</a></h2>
<p>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.</p>
<h2 id="stack-1-building-a-backbone-app-with-node.js-express-mongoose-and-mongodb"><a name="stack1">Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB</a></h2>
<p>The first stack we'll be looking at is:</p>
<li><a href="">Node.js</a></li>
<li><a href="">Express</a></li>
<li><a href="">Mongoose</a></li>
<li>and <a href="">MongoDB</a></li>
<p>with <a href="">Jade</a> used optionally as a view/templating engine.</p>
<h3 id="reviewing-the-stack">Reviewing the stack</h3>
<p>As you may know, node.js is an event-driven platform (built on the <a href="">V8</a> runtime), designed for writing fast, scalable network applications. It's reasonably lightweight, efficient and great for real-time applications that are data-intensive.</p>
<p>Express is a small web-development framework written with node.js, based on <a href="">Sinatra</a>. It supports a number of useful features such as intuitive views, robust routing and a focus on high performance.</p>
<p>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 <a href="">noSQL</a> 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 <a href="">relational</a> databases (rich functionality).</p>
<p>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.</p>
<p>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.</p>
<h3 id="practical">Practical</h3>
<p>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 <code>practicals\stacks\option2</code></p>
<p>(See <a href="">here</a> for the source)</p>
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> application_root = __dirname,
express = require(<span class="st">&quot;express&quot;</span>),
path = require(<span class="st">&quot;path&quot;</span>),
mongoose = require(<span class="ch">&#39;mongoose&#39;</span>);</code></pre>
<p>Next, create a new Express server. <code>express.createServer()</code> is a simple way of creating an instance of express.HTTPServer, which we'll be using to pass in our routes.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> app = <span class="kw">express</span>.<span class="fu">createServer</span>();</code></pre>
<p>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: <code>mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]</code></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">mongoose</span>.<span class="fu">connect</span>(<span class="ch">&#39;mongodb://localhost/my_database&#39;</span>);</code></pre>
<p>A Mongoose model for any Todo item can now be easily defined by passing a schema instance to <code>mongoose.model</code>. In our case the schema covers a Todo item's <code>text</code> content, its <code>done</code> state and <code>order</code> position in the overall Todo list.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">mongoose</span>.<span class="fu">model</span>(<span class="ch">&#39;Todo&#39;</span>, <span class="kw">new</span> <span class="kw">mongoose</span>.<span class="fu">Schema</span>({
<span class="dt">text</span>: <span class="kw">String</span>,
<span class="dt">done</span>: <span class="kw">Boolean</span>,
<span class="dt">order</span>: <span class="fu">Number</span>
<p>The <code>configure()</code> 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 <code>app.set('view engine', 'jade')</code>. We can avoid these if we wish to use plain HTML/JS for our templates instead.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">configure</span>(<span class="kw">function</span>(){
<span class="co">// the bodyParser middleware parses JSON request bodies</span>
<span class="kw">app</span>.<span class="fu">use</span>(<span class="kw">express</span>.<span class="fu">bodyParser</span>());
<span class="kw">app</span>.<span class="fu">use</span>(<span class="kw">express</span>.<span class="fu">methodOverride</span>());
<span class="kw">app</span>.<span class="fu">use</span>(<span class="kw">app</span>.<span class="fu">router</span>);
<span class="kw">app</span>.<span class="fu">use</span>(<span class="kw">express</span>.<span class="fu">static</span>(<span class="kw">path</span>.<span class="fu">join</span>(application_root, <span class="st">&quot;public&quot;</span>)));
<span class="kw">app</span>.<span class="fu">use</span>(<span class="kw">express</span>.<span class="fu">errorHandler</span>({ <span class="dt">dumpExceptions</span>: <span class="kw">true</span>, <span class="dt">showStack</span>: <span class="kw">true</span> }));
<span class="kw">app</span>.<span class="fu">set</span>(<span class="ch">&#39;views&#39;</span>, <span class="kw">path</span>.<span class="fu">join</span>(application_root, <span class="st">&quot;views&quot;</span>));
<span class="kw">app</span>.<span class="fu">set</span>(<span class="ch">&#39;view engine&#39;</span>, <span class="ch">&#39;jade&#39;</span>)
<p>Should you prefer to switch out Jade for an alternative view engine, this can be done fairly trivially. See the section under 'Templating' here: For example, to switch to EJS, you would simply write <code>app.set('view engine', 'ejs')</code></p>
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">get</span>(<span class="ch">&#39;/&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">res</span>.<span class="fu">send</span>(<span class="ch">&#39;Hello World&#39;</span>);
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">get</span>(<span class="ch">&#39;/todo&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">res</span>.<span class="fu">render</span>(<span class="ch">&#39;todo&#39;</span>, {<span class="dt">title</span>: <span class="st">&quot;Our sample application&quot;</span>});
<p>Next, we can see the first of our '/api/' routes.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">get</span>(<span class="ch">&#39;/api/todos&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">return</span> <span class="kw">Todo</span>.<span class="fu">find</span>(<span class="kw">function</span>(err, todos) {
<span class="kw">return</span> <span class="kw">res</span>.<span class="fu">send</span>(todos);
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">get</span>(<span class="ch">&#39;/api/todos/:id&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">return</span> <span class="kw">Todo</span>.<span class="fu">findById</span>(<span class="kw">req.params</span>.<span class="fu">id</span>, <span class="kw">function</span>(err, todo) {
<span class="kw">if</span> (!err) {
<span class="kw">return</span> <span class="kw">res</span>.<span class="fu">send</span>(todo);
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">put</span>(<span class="ch">&#39;/api/todos/:id&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">return</span> <span class="kw">Todo</span>.<span class="fu">findById</span>(<span class="kw">req.params</span>.<span class="fu">id</span>, <span class="kw">function</span>(err, todo) {
<span class="kw">todo</span>.<span class="fu">text</span> = <span class="kw">req.body</span>.<span class="fu">text</span>;
<span class="kw">todo</span>.<span class="fu">done</span> = <span class="kw">req.body</span>.<span class="fu">done</span>;
<span class="kw">todo</span>.<span class="fu">order</span> = <span class="kw">req.body</span>.<span class="fu">order</span>;
<span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">save</span>(<span class="kw">function</span>(err) {
<span class="kw">if</span> (!err) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;updated&quot;</span>);
<span class="kw">return</span> <span class="kw">res</span>.<span class="fu">send</span>(todo);
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">post</span>(<span class="ch">&#39;/api/todos&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">var</span> todo;
todo = <span class="kw">new</span> Todo({
<span class="dt">text</span>: <span class="kw">req.body</span>.<span class="fu">text</span>,
<span class="dt">done</span>: <span class="kw">req.body</span>.<span class="fu">done</span>,
<span class="dt">order</span>: <span class="kw">req.body</span>.<span class="fu">order</span>
<span class="kw">todo</span>.<span class="fu">save</span>(<span class="kw">function</span>(err) {
<span class="kw">if</span> (!err) {
<span class="kw">return</span> <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;created&quot;</span>);
<span class="kw">return</span> <span class="kw">res</span>.<span class="fu">send</span>(todo);
<p>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.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">delete</span>(<span class="ch">&#39;/api/todos/:id&#39;</span>, <span class="kw">function</span>(req, res){
<span class="kw">return</span> <span class="kw">Todo</span>.<span class="fu">findById</span>(<span class="kw">req.params</span>.<span class="fu">id</span>, <span class="kw">function</span>(err, todo) {
<span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">remove</span>(<span class="kw">function</span>(err) {
<span class="kw">if</span> (!err) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;removed&quot;</span>);
<span class="kw">return</span> <span class="kw">res</span>.<span class="fu">send</span>(<span class="ch">&#39;&#39;</span>)
<p>Finally, this last line is to ensure we're only listening on the port app.js is running.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">app</span>.<span class="fu">listen</span>(<span class="dv">3000</span>);</code></pre>
<p><strong>script.js - updating our Backbone.js app</strong></p>
<p>In the <code>/public/js</code> 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 <a href="">script.js</a>. In order to change the application to work with our new back-end, we'll need to make some very minor changes to this.</p>
<p>Reviewing <code>window.TodoList</code> (a Backbone Collection), you'll notice that it has a property called <code>localStorage</code>, which uses the Backbone <a href="">localStorage</a> adapter in order to facilitate storing data using the browser's localStorage features.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">window</span>.<span class="fu">TodoList</span> = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="co">// Reference to this collection&#39;s model.</span>
<span class="dt">model</span>: Todo,
<span class="co">// Save all of the todo items under the `&quot;todos&quot;` namespace.</span>
<span class="co">// Typically, this should be a unique name within your application</span>
<span class="dt">localStorage</span>: <span class="kw">new</span> Store(<span class="st">&quot;todos&quot;</span>),</code></pre>
<p>In order to switch it over to our RESTful backend, we're going to make use of the <code>url</code> property or function on a collection to reference its location on the server. Models inside of a collection then use <code>url</code> 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 <code>url</code> to.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="co">// localStorage: new Store(&quot;todos&quot;),</span>
<span class="dt">url</span>: <span class="ch">&#39;/api/todos&#39;</span>,</code></pre>
<p>This is the only change necessary to our existing Backbone application in order to get things working. Pretty easy, right?</p>
<p>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.</p>
<pre class="sourceCode html"><code class="sourceCode html">// Todo App Interface
h1 Todos
input#new-todo(placeholder=<span class="dv">&amp;quot;</span>What needs to be done?<span class="dv">&amp;quot;</span>, type=<span class="dv">&amp;quot;</span>text<span class="dv">&amp;quot;</span>)
span.ui-tooltip-top(style=<span class="dv">&amp;quot;</span>display:none;<span class="dv">&amp;quot;</span>) Press Enter to save this task
// Templates
script#item-template(type=<span class="dv">&amp;quot;</span>text/template<span class="dv">&amp;quot;</span>)
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>todo <span class="dv">&amp;lt;</span>%= done ? &#39;done&#39; : &#39;&#39; %<span class="dv">&amp;gt;&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>input class=<span class="dv">&amp;quot;</span>check<span class="dv">&amp;quot;</span> type=<span class="dv">&amp;quot;</span>checkbox<span class="dv">&amp;quot;</span> <span class="dv">&amp;lt;</span>%= done ? &#39;checked=<span class="dv">&amp;quot;</span>checked<span class="dv">&amp;quot;</span>&#39; : &#39;&#39; %<span class="dv">&amp;gt;</span> /<span class="dv">&amp;gt;</span>
input.todo-input(type=<span class="dv">&amp;quot;</span>text<span class="dv">&amp;quot;</span>, <span class="dv">&amp;quot;</span>value<span class="dv">&amp;quot;</span>=<span class="dv">&amp;quot;&amp;quot;</span>)
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
script#stats-template(type=<span class="dv">&amp;quot;</span>text/template<span class="dv">&amp;quot;</span>)
<span class="dv">&amp;lt;</span>% if (total) { %<span class="dv">&amp;gt;</span>
span.number <span class="dv">&amp;lt;</span>%= remaining %<span class="dv">&amp;gt;</span>
span.word <span class="dv">&amp;lt;</span>%= remaining == 1 ? &#39;item&#39; : &#39;items&#39; %<span class="dv">&amp;gt;</span>
| left.
<span class="dv">&amp;lt;</span>% } %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>% if (done) { %<span class="dv">&amp;gt;</span>
a(href=<span class="dv">&amp;quot;</span>#<span class="dv">&amp;quot;</span>)
| Clear
span.number-done <span class="dv">&amp;lt;</span>%= done %<span class="dv">&amp;gt;</span>
| completed
span.word-done <span class="dv">&amp;lt;</span>%= done == 1 ? &#39;item&#39; : &#39;items&#39; %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>% } %<span class="dv">&amp;gt;</span></code></pre>
<pre class="sourceCode html"><code class="sourceCode html">!!! 5
//if lt IE 6
<span class="dv">&amp;lt;</span>html class=<span class="dv">&amp;quot;</span>no-js ie6 oldie<span class="dv">&amp;quot;</span> lang=<span class="dv">&amp;quot;</span>en<span class="dv">&amp;quot;&amp;gt;</span>
//if IE 7
<span class="dv">&amp;lt;</span>html class=<span class="dv">&amp;quot;</span>no-js ie7 oldie<span class="dv">&amp;quot;</span> lang=<span class="dv">&amp;quot;</span>en<span class="dv">&amp;quot;&amp;gt;</span>
//if IE 8
<span class="dv">&amp;lt;</span>html class=<span class="dv">&amp;quot;</span>no-js ie8 oldie<span class="dv">&amp;quot;</span> lang=<span class="dv">&amp;quot;</span>en<span class="dv">&amp;quot;&amp;gt;</span>
//if gt IE 8
<span class="dv">&amp;lt;</span>!--<span class="dv">&amp;gt;</span> <span class="dv">&amp;lt;</span>html class=<span class="dv">&amp;quot;</span>no-js<span class="dv">&amp;quot;</span> lang=<span class="dv">&amp;quot;</span>en<span class="dv">&amp;quot;&amp;gt;</span> <span class="dv">&amp;lt;</span>!--
meta(charset=<span class="dv">&amp;quot;</span>utf-8<span class="dv">&amp;quot;</span>)
meta(http-equiv=<span class="dv">&amp;quot;</span>X-UA-Compatible<span class="dv">&amp;quot;</span>, content=<span class="dv">&amp;quot;</span>IE=edge,chrome=1<span class="dv">&amp;quot;</span>)
meta(name=<span class="dv">&amp;quot;</span>description<span class="dv">&amp;quot;</span>, content=<span class="dv">&amp;quot;&amp;quot;</span>)
meta(name=<span class="dv">&amp;quot;</span>author<span class="dv">&amp;quot;</span>, content=<span class="dv">&amp;quot;&amp;quot;</span>)
meta(name=<span class="dv">&amp;quot;</span>viewport<span class="dv">&amp;quot;</span>, content=<span class="dv">&amp;quot;</span>width=device-width,initial-scale=1<span class="dv">&amp;quot;</span>)
// CSS concatenated and minified via ant build script
link(rel=<span class="dv">&amp;quot;</span>stylesheet<span class="dv">&amp;quot;</span>, href=<span class="dv">&amp;quot;</span>css/style.css<span class="dv">&amp;quot;</span>)
// end CSS
script(src=<span class="dv">&amp;quot;</span>js/libs/modernizr-2.0.6.min.js<span class="dv">&amp;quot;</span>)
#main(role=<span class="dv">&amp;quot;</span>main<span class="dv">&amp;quot;</span>)!=body
//! end of #container
script(src=<span class="dv">&amp;quot;</span>//<span class="dv">&amp;quot;</span>)
window.jQuery || document.write(&#39;<span class="dv">&amp;lt;</span>script src=<span class="dv">&amp;quot;</span>js/libs/jquery-1.6.2.min.js<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>\\/script<span class="dv">&amp;gt;</span>&#39;)
// scripts concatenated and minified via ant build script
script(src=<span class="dv">&amp;quot;</span>js/mylibs/underscore.js<span class="dv">&amp;quot;</span>)
script(src=<span class="dv">&amp;quot;</span>js/mylibs/backbone.js<span class="dv">&amp;quot;</span>)
script(defer, src=<span class="dv">&amp;quot;</span>js/plugins.js<span class="dv">&amp;quot;</span>)
script(defer, src=<span class="dv">&amp;quot;</span>js/script.js<span class="dv">&amp;quot;</span>)
// end scripts
// Change UA-XXXXX-X to be your site&#39;s ID
window._gaq = [[&#39;_setAccount&#39;,&#39;UAXXXXXXXX1&#39;],[&#39;_trackPageview&#39;],[&#39;_trackPageLoadTime&#39;]];
Modernizr.load({load: (&#39;https:&#39; == location.protocol ? &#39;//ssl&#39; : &#39;//www&#39;) + &#39;;});
//if lt IE 7
script(src=<span class="dv">&amp;quot;</span>//<span class="dv">&amp;quot;</span>)
<span class="dv">&amp;lt;</span>/html<span class="dv">&amp;gt;</span></code></pre>
<p>Alternatively, a static version of our index which doesn't rely on Jade can be put together as follows. See <a href="">here</a> for the complete file or below for a sample.</p>
<pre class="sourceCode html"><code class="sourceCode html"> <span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>container<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>main<span class="dv">&amp;quot;</span> role=<span class="dv">&amp;quot;</span>main<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>!-- Todo App Interface--<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>todoapp<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>title<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>h1<span class="dv">&amp;gt;</span>Todos<span class="dv">&amp;lt;</span>/h1<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>content<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>create-todo<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>input id=<span class="dv">&amp;quot;</span>new-todo<span class="dv">&amp;quot;</span> placeholder=<span class="dv">&amp;quot;</span>What needs to be done?<span class="dv">&amp;quot;</span> type=
<span class="dv">&amp;quot;</span>text<span class="dv">&amp;quot;</span> /<span class="dv">&amp;gt;&amp;lt;</span>span style=<span class="dv">&amp;quot;</span>display:none;<span class="dv">&amp;quot;</span> class=<span class="dv">&amp;quot;</span>ui-tooltip-top<span class="dv">&amp;quot;&amp;gt;</span>Press Enter to
save this task<span class="dv">&amp;lt;</span>/span<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>todos<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>ul id=<span class="dv">&amp;quot;</span>todo-list<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>/ul<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>div id=<span class="dv">&amp;quot;</span>todo-stats<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>!-- Templates--<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>script id=<span class="dv">&amp;quot;</span>item-template<span class="dv">&amp;quot;</span> type=<span class="dv">&amp;quot;</span>text/template<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>todo <span class="dv">&amp;lt;</span>%= done ? &#39;done&#39; : &#39;&#39; %<span class="dv">&amp;gt;&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>display<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>input class=<span class="dv">&amp;quot;</span>check<span class="dv">&amp;quot;</span> type=<span class="dv">&amp;quot;</span>checkbox<span class="dv">&amp;quot;</span> <span class="dv">&amp;lt;</span>%= done ? &#39;checked=<span class="dv">&amp;quot;</span>checked<span class="dv">&amp;quot;</span>&#39; : &#39;&#39; %<span class="dv">&amp;gt;</span> /<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>todo-text<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>/div<span class="dv">&amp;gt;&amp;lt;</span>span id=<span class="dv">&amp;quot;</span>todo-destroy<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>/span<span class="dv">&amp;gt;&amp;lt;</span>/div<span class="dv">&amp;gt;&amp;lt;</span>div class=<span class="dv">&amp;quot;</span>edit<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>input type=<span class="dv">&amp;quot;</span>text<span class="dv">&amp;quot;</span> value=<span class="dv">&amp;quot;&amp;quot;</span> class=<span class="dv">&amp;quot;</span>todo-input<span class="dv">&amp;quot;</span>/<span class="dv">&amp;gt;&amp;lt;</span>/div<span class="dv">&amp;gt;&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/script<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>script id=<span class="dv">&amp;quot;</span>stats-template<span class="dv">&amp;quot;</span> type=<span class="dv">&amp;quot;</span>text/template<span class="dv">&amp;quot;&amp;gt;</span>
<span class="dv">&amp;lt;</span>% if (total) { %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>todo-count<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>number<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>%= remaining %<span class="dv">&amp;gt;</span> <span class="dv">&amp;lt;</span>/span<span class="dv">&amp;gt;&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>word<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>%= remaining == 1 ? &#39;item&#39; : &#39;items&#39; %<span class="dv">&amp;gt;&amp;lt;</span>/span<span class="dv">&amp;gt;</span> left.
<span class="dv">&amp;lt;</span>/span<span class="dv">&amp;gt;&amp;lt;</span>% } %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>% if (done) { %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>todo-clear<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>a href=<span class="dv">&amp;quot;</span>#<span class="dv">&amp;quot;&amp;gt;</span> Clear
<span class="dv">&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>number-done<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>%= done %<span class="dv">&amp;gt;&amp;lt;</span>/span<span class="dv">&amp;gt;</span> completed
<span class="dv">&amp;lt;</span>span class=<span class="dv">&amp;quot;</span>word-done<span class="dv">&amp;quot;&amp;gt;&amp;lt;</span>%= done == 1 ? &#39;item&#39; : &#39;items&#39; %<span class="dv">&amp;gt;&amp;lt;</span>/span<span class="dv">&amp;gt;&amp;lt;</span>/a<span class="dv">&amp;gt;&amp;lt;</span>/span<span class="dv">&amp;gt;&amp;lt;</span>% } %<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/script<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>/div<span class="dv">&amp;gt;</span>
<span class="dv">&amp;lt;</span>!--! end of #container--<span class="dv">&amp;gt;</span></code></pre>
<h3 id="practical-setup">Practical Setup</h3>
<p>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.</p>
<h4 id="mongodb">MongoDB</h4>
<p>Once you've downloaded <a href="">MongoDB</a>, you'll need to complete two steps to get it up and running.</p>
<p><strong>Data directories</strong></p>
<p>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:</p>
<pre class="sourceCode html"><code class="sourceCode html">sudo mkdir -p /data/db/
sudo chown `id -u` /data/db</code></pre>
<p><strong>Running and connecting to your server</strong></p>
<p>Once this is done, open up two terminal windows.</p>
<p>In the first, <code>cd</code> to your MongoDB bin directory or type in the complete path to it. You'll need to start <cpde>mongod`.</p>
<pre class="sourceCode html"><code class="sourceCode html">$ ./bin/mongod</code></pre>
<p>Next, in the second terminal, start the `mongo</code shell which will connect up to localhost by default.
$ ./bin/mongo
That's it!.
####Express and Mongoose
Option 1 (HTML) and Option 2 (Jade) of the practical download both come with an bash script. This allows you to easily install Express, Mongoose, Jade (and optionally MongoDB if you prefer to) through npm (the node package manager).
* Make sure you have Node.js installed. If not, you can grab it [here](
* Next run `$ ./` at the terminal to install the rest of our dependencies. To see the exact contents of the file, see below:
npm install express
npm install mongodb --mongodb:native
npm install mongoose
npm install jade
* 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:
git clone git://
cd option2
node app.js
For option1 (without Jade), simply cd into option1 and run `node app.js` from there.
Finally, either of the example apps can now be accessed by navigating to:
* Option 1: `http://localhost:3000/static.html`
* Option 2: `http://localhost:3000/todo`
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.
#<a name="stack2">Building Backbone.js Apps With Ruby, Sinatra, MongoDB and Haml</a></p>
<h2 id="introduction-1">Introduction</h2>
<p>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 <a href="">Sinatra</a> - a DSL (domain specific language) for rapidly creating web applications in Ruby. Similar to the <a href="">section</a> 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.</p>
<h2 id="what-is-sinatra">What Is Sinatra?</h2>
<p>In the past, you've likely come across or used <a href="">Ruby on Rails</a> (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.</p>
<p>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.</p>
<p>What Sinatra does have is a <strong>minimal</strong> 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.</p>
<p>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.</p>
<p>Sinatra takes a more straight-forward approach, providing us with the most simple path to handling routing. By declaring <code>get</code>,<code>post</code>, <code>put</code> or <code>delete</code> actions, we can inform Sinatra to add a new route, which we can then have respond to requests.</p>
<p>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.</p>
<h2 id="getting-started-with-sinatra">Getting Started With Sinatra</h2>
<p>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 &quot;Hello World&quot;, we'll start with a similar example.</p>
<p>Note: Before beginning this section, I recommend installing Sinatra on your system. A guide to doing this can be found in the <a href="#preq">prerequisites</a> section lower down in the article.</p>
<h3 id="routes">Routes</h3>
<p>As mentioned, Sinatra allows us to define new routes using HTTP actions. Semantically, a route follows quite a simple structure:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">&lt;a <span class="dt">HTTP</span> action&gt; &lt;the desired route&gt; <span class="kw">do</span>
<span class="co"># some behaviour</span>
<span class="kw">end</span></code></pre>
<p>A tiny route that outputs a &quot;Hello World&quot;-like message when we attempt to &quot;get&quot; the root could thus be written as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">require <span class="st">&#39;sinatra&#39;</span>
get <span class="st">&#39;/&#39;</span> <span class="kw">do</span>
<span class="st">&quot;Hello World! Is it me you&#39;re looking for?&quot;</span>
<span class="kw">end</span></code></pre>
<p>To run this snippet, we can can simply save it to a local '.rb' file and execute it as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">ruby -rubygems example.rb</code></pre>
<p>If we now navigated to http://localhost:4567 in our browser we could now see the application running successfully.</p>
<p>The HTTP verbs we commonly work with when writing RESTful web services are: <code>get</code>, <code>post</code>, <code>delete</code> and <code>put</code>. As we now know, all Sinatra routes are basically HTTP actions (`<code>get</code> 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.</p>
<p>Here's an example of a skeleton service we could put together supporting four common HTTP actions: ruby ``` get '/items' do # list all items available end</p>
<p>get '/item/:id' do # get a single item end</p>
<p>post '/item' do # create a new item end</p>
<p>put '/item/:id' do # update an existing item end</p>
<p>delete '/item/:id' do # delete an item end ```</p>
<p>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 <code>/item/:id</code>). We can actually access the content of these routes using the <code>params</code> hash as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/item/:id&#39;</span> <span class="kw">do</span>
<span class="co"># this matches &quot;GET /item/10&quot; and &quot;GET /item/11&quot;</span>
<span class="co"># params[:id] is &quot;10&quot; or &quot;11&quot;</span>
<span class="st">&quot;You reached </span><span class="ot">#{</span>params[<span class="st">:id</span>]<span class="ot">}</span><span class="st">&quot;</span>
<span class="kw">end</span></code></pre>
<p>Sinatra also supports route matching via splats, wildcards and regular expressions. For more information on this I recommend reading the official <a href="">docs</a>. Let's now take a look at handlers.</p>
<p>Sinatra includes convenient handler methods for tasks such as redirection, halting and passing.</p>
<h4 id="redirection">Redirection</h4>
<p>A simple route supporting redirection which returns a 302 response can be written as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/items&#39;</span> <span class="kw">do</span>
redirect <span class="st">&#39;/items/welcome&#39;</span>
<span class="kw">end</span></code></pre>
<p>And if we wish to pass additional parameters such as arguments we can do so like this: redirect '', 'Oops! I think we have a problem!'</p>
<h4 id="halting">Halting</h4>
<p>To immediately stop a request (halting) we can use 'halt'. Heres an example of halting a request where we specify the message body:</p>
<p><code>halt &quot;who goes there!?&quot;</code></p>
<h4 id="passing">Passing</h4>
<p>'Passing' is the concept of deferring processing of a block to the next matching route. We do this using <code>pass</code>. In the following example if a parameter isnt the username we expect (rick-astley) we simply pass it on:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/members/:username&#39;</span> <span class="kw">do</span>
pass <span class="kw">unless</span> params[<span class="st">:username</span>] == <span class="st">&#39;rick-astley&#39;</span>
<span class="st">&#39;Never gonna give you up, never gonna let you down&#39;</span>
<span class="kw">end</span>
get <span class="st">&#39;/member/*&#39;</span> <span class="kw">do</span>
<span class="st">&#39;Welcome!&#39;</span>
<span class="kw">end</span></code></pre>
<p>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:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">enable <span class="st">:sessions</span></code></pre>
<p>You can then use the session handling capabilities as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/items&#39;</span> <span class="kw">do</span>
session[<span class="st">&#39;visitCounter&#39;</span>] ||= <span class="dv">0</span>;
session[<span class="st">&#39;visitCounter&#39;</span>] += <span class="dv">1</span>;
<span class="st">&quot;This page has been accessed </span><span class="ot">#{</span>session[<span class="st">&#39;visitCounter&#39;</span>]<span class="ot">}</span><span class="st"> times&quot;</span>
<span class="kw">end</span></code></pre>
<p>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 <a href="">here</a>.</p>
<p>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.</p>
<h2 id="templating-and-haml">Templating And HAML</h2>
<p>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 <code>views</code> directory of our application.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/items&#39;</span> <span class="kw">do</span>
erb <span class="st">:default</span>
<span class="co"># renders views/default.erb</span>
<span class="kw">end</span></code></pre>
<p>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:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>
<span class="er">&lt;</span>%= data %&gt;
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>Haml is a popular alternative to ERB which offers an abstract syntax for writing application templates. It has been said to be:</p>
<li>Straight-forward to learn</li>
<li>Very easy to read and use for visually expressing a hierarchy of DOM elements</li>
<li>Popular with web designers as it builds on top of CSS syntax</li>
<li>Well documented with a large community backing it</li>
<li>Almost as fast as ERB</li>
<p>For the purpose of comparison, below we can see an ERB template compared to it's Haml equivalent.</p>
<h4 id="erb">ERB</h4>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;todo&quot;</span><span class="ot"> id=</span><span class="st">&quot;content&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;h2</span><span class="ot"> class=</span><span class="st">&quot;entry_title&quot;</span><span class="kw">&gt;</span><span class="er">&lt;</span>%= h @todo.title %&gt;<span class="kw">&lt;/h2&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;entry_link&quot;</span><span class="kw">&gt;</span><span class="er">&lt;</span>%= link_to(&#39;link&#39;, %&gt;<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;/div&gt;</span></code></pre>
<h4 id="haml">Haml</h4>
<pre class="sourceCode html"><code class="sourceCode html">.todo#content
%h2.entry_title= @todo.title
.entry_link= link_to(&#39;link&#39;,</code></pre>
<p>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).</p>
<p>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.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="ot">%</span>h1 This is some h1 text
<span class="ot">%</span>h2 This is some h2 text<span class="ot">.</span>
<span class="st">%p Now we have a line containing a single instance variable: @content</span>
<span class="st">%p= @content</span>
<span class="st">%p Embedding Ruby code in the middle of a line can be done using ==</span><span class="ot">.</span>
<span class="ot">%</span>p<span class="ot">==</span> <span class="dt">Here</span> is an example: <span class="co">#{@foobar}</span>
<span class="ot">%</span>p We can also add attributes using <span class="ot">{}</span>
<span class="ot">%</span>p<span class="ot">{</span><span class="st">:style =&gt; &quot;color:green&quot;</span><span class="ot">}</span> <span class="dt">We</span> just made this paragraph green!
<span class="ot">%</span>p You<span class="ot">&#39;</span><span class="st">ll want to apply classes and ids to your DOM, too.</span>
<span class="st"> This has the foo class</span>
<span class="st"> This has the bar class</span>
<span class="st">%p#foobar This has the foobar id</span>
<span class="st"> Or you can combine them!</span>
<span class="st">%p Nesting can be done like this</span>
<span class="st">%p</span>
<span class="st"> Or even like this</span></code></pre>
<p>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.</p>
<h1 id="mongodb-ruby-driver">MongoDB Ruby Driver</h1>
<h2 id="getting-started">Getting started</h2>
<p>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:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">require <span class="st">&#39;mongo&#39;</span>
<span class="co"># where &#39;learning-mongo&#39; is the name of our database:</span>
db = <span class="dt">Connection</span>.new.db(<span class="st">&#39;learning-mongo&#39;</span>);</code></pre>
<p>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?:</p>
<p><code>ruby notes = db.collection('notes')</code> Something interesting worth noting is that at this point, we haven't actually created the database nor the collection we're referencing above.</p>
<p>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.</p>
<p>A new note could be defined using key/value pairs as follows and then inserted into 'learning-mongo' using <code>collection.insert()</code>:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">our_note = { <span class="st">:text</span> =&gt; <span class="st">&#39;Remember the milk&#39;</span>, <span class="st">:remindInterval</span> =&gt; <span class="st">&#39;weekly&#39;</span>}
note_id = notes.insert(our_note)</code></pre>
<p>What is returned from inserting a note into the notes collection is an <code>ObjectId</code> reference for the note from Mongo. This is useful as we can re-use it to locate the same document in our database.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">note = notes.find( <span class="st">:id</span> =&gt; note_id ).first</code></pre>
<p>This can also be used in conjunction with Mongo's <code>collection.update()</code> method and <a href="">query</a> operators (i.e <code>$set</code>) to replace fields in an existing document.</p>
<p>We might update an entire document as follows:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">note = notes.find( <span class="st">:id</span> =&gt; note_id ).first
note[<span class="st">:text</span>] = <span class="st">&#39;Remember the bread&#39;</span>
notes.update({ <span class="st">:_id</span> =&gt; note_id }, note)</code></pre>
<p>or using <code>$set</code>, update an existing document without overwriting the entire object as like this:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">notes.update({ <span class="st">:_id</span> =&gt; note_id }, <span class="st">&#39;$set&#39;</span> =&gt; { <span class="st">:text</span> = &gt; <span class="st">&#39;Remember the bread&#39;</span> })</code></pre>
<p>Useful to know: Almost each MongoDB document has an _id field as it's first attribute. This can normally be of any type, however a special BSON datatype is provided for object ids. It's a 12-byte binary value that has a high probability of being unique when allocated.</p>
<p>Note: Whilst we opted for the MongoDB Ruby Driver for this stack, you may also be interested in <strong>DataMapper</strong> - 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 <a href="">project page</a>. <a href="">Sinatra: The Book</a> also contains a brief tutorial on DataMapper for anyone interested in exploring it further.</p>
<h1 id="practical-1">Practical</h1>
<p>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.</p>
<p>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.</p>
<h3 id="installing-the-prerequisites"><a id="preq">Installing The Prerequisites</a></h3>
<h4 id="ruby">Ruby</h4>
<p>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:</p>
<p><code>$ ruby -v</code></p>
<p>The output of this will either be the version of Ruby installed or an error complaining that Ruby wasn't found.</p>
<p>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 Alternatively, (RVM)[] (Ruby Version Manager) is a command-line tool that allows you to easily install and manage multiple ruby environments with ease.</p>
<h4 id="ruby-gems">Ruby Gems</h4>
<p>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.</p>
<p>On OSX, Linux or Windows go to <a href=""></a> and download the latest version of Ruby Gems. Once downloaded, open up a terminal, navigate to the folder where this resides and enter:</p>
<pre><code>$&gt; tar xzvf rubygems.tgz
$&gt; cd rubygems
$&gt; sudo ruby setup.rb</code></pre>
<p>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:</p>
<p><code>$ sudo ln -s /usr/bin/gem1.8.17 /usr/bin/gem</code></p>
<p>To check that Ruby Gems has been correctly installed, type the following into your terminal:</p>
<pre><code>$ gem -v</code></pre>
<h4 id="sinatra">Sinatra</h4>
<p>With Ruby Gems setup, we can now easily install Sinatra. For Linux or OSX type this in your terminal:</p>
<p><code>$ sudo gem install sinatra</code></p>
<p>and if you're on Windows, enter the following at a command prompt:</p>
<p><code>c:\\ &gt; gem install sinatra</code></p>
<h4 id="haml-1">Haml</h4>
<p>As with other DSLs and frameworks, Sinatra supports a wide range of different templating engines. <a href="">ERB</a> is the one most often recommended by the Sinatra camp, however as a part of this chapter, we're going to explore the use of <a href="">Haml</a> to define our application templates.</p>
<p>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).</p>
<p>Installing Haml can be done in just a line using Ruby Gems as follows:</p>
<p><code>$ gem install haml</code></p>
<h4 id="mongodb-1">MongoDB</h4>
<p>If you haven't already downloaded and installed MongoDB from an earlier chapter, please <a href="">do so</a> now. With Ruby Gems, Mongo can be installed in just one line:</p>
<p><code>$ gem install mongodb</code></p>
<p>We now require two further steps to get everything up and running.</p>
<h5 id="data-directories">1.Data directories</h5>
<p>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:</p>
<pre><code>sudo mkdir -p /data/db/
sudo chown `id -u` /data/db</code></pre>
<h5 id="running-and-connecting-to-your-server">2.Running and connecting to your server</h5>
<p>Once this is done, open up two terminal windows.</p>
<p>In the first, cd to your MongoDB bin directory or type in the complete path to it. You'll need to start mongod.</p>
<pre><code>$ ./bin/mongod</code></pre>
<p>Finally, in the second terminal, start the mongo shell which will connect up to localhost by default.</p>
<pre><code>$ ./bin/mongo</code></pre>
<h4 id="mongodb-ruby-driver-1">MongoDB Ruby Driver</h4>
<p>As we'll be using the <a href="">MongoDB Ruby Driver</a>, we'll also require the following gems:</p>
<p>The gem for the driver itself:</p>
<pre><code>$ gem install mongo</code></pre>
<p>and the driver's other prerequisite, bson:</p>
<pre><code>$ gem install bson_ext</code></pre>
<p>This is basically a collection of extensions used to increase serialization speed.</p>
<p>That's it for our prerequisites!.</p>
<h2 id="tutorial">Tutorial</h2>
<p>To get started, let's get a local copy of the practical application working on our system.</p>
<h3 id="application-files">Application Files</h3>
<p>Clone <a href="">this</a> repository and navigate to <code>/practicals/stacks/option3</code>. Now run the following lines at the terminal:</p>
<pre><code>ruby app.rb</code></pre>
<p>Finally, navigate to <code>http://localhost:4567/todo</code> to see the application running successfully.</p>
<p><strong>Note:</strong> The Haml layout files for Option 3 can be found in the /views folder.</p>
<p>The directory structure for our practical application is as follows:</p>
<p>The <code>public</code> 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 <code>public/js/scripts.js</code> (however, this can of course be expanded into sub-directories for each component if desired).</p>
<p><code>scripts.js</code> contains the following Backbone component definitions:</p>
<p><code>app.rb</code> is the small Sinatra application that powers our backend API.</p>
<p>Lastly, the <code>views</code> directory hosts the Haml source files for our application's index and templates, both of which are compiled to standard HTML markup at runtime.</p>
<p>These can be viewed along with other note-worthy snippets of code from the application below.</p>
<h3 id="backbone">Backbone</h3>
<h4 id="views-2">Views</h4>
<p>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 <code>Todos.fetch()</code> in the <code>initialize()</code> method where we also bind to the relevant events on the <code>Todos</code> collection for when items are added or changed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Our overall **AppView** is the top-level piece of UI.</span>
<span class="kw">var</span> AppView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="co">// Instead of generating a new element, bind to the existing skeleton of</span>
<span class="co">// the App already present in the HTML.</span>
<span class="dt">el</span>: $(<span class="st">&quot;#todoapp&quot;</span>),
<span class="co">// Our template for the line of statistics at the bottom of the app.</span>
<span class="dt">statsTemplate</span>: <span class="kw">_</span>.<span class="fu">template</span>($(<span class="ch">&#39;#stats-template&#39;</span>).<span class="fu">html</span>()),
<span class="co">// Delegated events for creating new items, and clearing completed ones.</span>
<span class="dt">events</span>: {
<span class="st">&quot;keypress #new-todo&quot;</span>: <span class="st">&quot;createOnEnter&quot;</span>,
<span class="st">&quot;keyup #new-todo&quot;</span>: <span class="st">&quot;showTooltip&quot;</span>,
<span class="st">&quot;click .todo-clear a&quot;</span>: <span class="st">&quot;clearCompleted&quot;</span>
<span class="co">// At initialization</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="st">&quot;#new-todo&quot;</span>);
<span class="kw">Todos</span>.<span class="fu">on</span>(<span class="ch">&#39;add&#39;</span>, <span class="kw">this</span>.<span class="fu">addOne</span>, <span class="kw">this</span>);
<span class="kw">Todos</span>.<span class="fu">on</span>(<span class="ch">&#39;reset&#39;</span>, <span class="kw">this</span>.<span class="fu">addAll</span>, <span class="kw">this</span>);
<span class="kw">Todos</span>.<span class="fu">on</span>(<span class="ch">&#39;all&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span>);
<span class="kw">Todos</span>.<span class="fu">fetch</span>();
<span class="co">// Re-rendering the App just means refreshing the statistics -- the rest</span>
<span class="co">// of the app doesn&#39;t change.</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.$(<span class="ch">&#39;#todo-stats&#39;</span>).<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">statsTemplate</span>({
<span class="dt">total</span>: <span class="kw">Todos</span>.<span class="fu">length</span>,
<span class="dt">done</span>:
<h3 id="collections-1">Collections</h3>
<p>In the TodoList collection below, we've set the <code>url</code> property to point to <code>/api/todos</code> 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.</p>
<p>For the sake of thoroughness, our API will also support returning the data for a specific Todo item via <code>/api/todos/itemID</code>. We'll take a look at this again when writing the Ruby code powering our backend.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="co">// Todo Collection</span>
<span class="kw">var</span> TodoList = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="co">// Reference to this collection&#39;s model.</span>
<span class="dt">model</span>: Todo,
<span class="co">// Save all of the todo items under the `&quot;todos&quot;` namespace.</span>
<span class="co">// localStorage: new Store(&quot;todos&quot;),</span>
<span class="dt">url</span>: <span class="ch">&#39;/api/todos&#39;</span>,
<span class="co">// Filter down the list of all todo items that are finished.</span>
<span class="dt">done</span>: <span class="kw">function</span>() {
<span class="kw">return</span> <span class="kw">this</span>.<span class="fu">filter</span>(<span class="kw">function</span>(todo){ <span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">get</span>(<span class="ch">&#39;done&#39;</span>); });
<span class="co">// Filter down the list to only todo items that are still not finished.</span>
<span class="dt">remaining</span>: <span class="kw">function</span>() {
<span class="kw">return</span> <span class="kw">this</span>.<span class="fu">without</span>.<span class="fu">apply</span>(<span class="kw">this</span>, <span class="kw">this</span>.<span class="fu">done</span>());
<span class="co">// We keep the Todos in sequential order, despite being saved by unordered</span>
<span class="co">// GUID in the database. This generates the next order number for new items.</span>
<span class="dt">nextOrder</span>: <span class="kw">function</span>() {
<span class="kw">if</span> (!<span class="kw">this</span>.<span class="fu">length</span>) <span class="kw">return</span> <span class="dv">1</span>;
<span class="kw">return</span> <span class="kw">this</span>.<span class="fu">last</span>().<span class="fu">get</span>(<span class="ch">&#39;order&#39;</span>) + <span class="dv">1</span>;
<span class="co">// Todos are sorted by their original insertion order.</span>
<span class="dt">comparator</span>: <span class="kw">function</span>(todo) {
<span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">get</span>(<span class="ch">&#39;order&#39;</span>);
<h3 id="model">Model</h3>
<p>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 <code>model.url()</code> within the below would return the relative URL where a specific Todo item could be located on the server.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// Our basic **Todo** model has `text`, `order`, and `done` attributes.</span>
<span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">idAttribute</span>: <span class="st">&quot;_id&quot;</span>,
<span class="co">// Default attributes for a todo item.</span>
<span class="dt">defaults</span>: <span class="kw">function</span>() {
<span class="kw">return</span> {
<span class="dt">done</span>: <span class="kw">false</span>,
<span class="dt">order</span>: <span class="kw">Todos</span>.<span class="fu">nextOrder</span>()
<span class="co">// Toggle the `done` state of this todo item.</span>
<span class="dt">toggle</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">save</span>({<span class="dt">done</span>: !<span class="kw">this</span>.<span class="fu">get</span>(<span class="st">&quot;done&quot;</span>)});
<h3 id="rubysinatra">Ruby/Sinatra</h3>
<p>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.</p>
<p>We want to make sure that for any operations changing underlying data (create, update, delete) that our Mongo data store correctly reflects these.</p>
<h3 id="app.rb">app.rb</h3>
<p>For <code>app.rb</code>, we first define the dependencies required by our application. These include Sinatra, Ruby Gems, the MongoDB Ruby driver and the JSON gem.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">require <span class="st">&#39;rubygems&#39;</span>
require <span class="st">&#39;sinatra&#39;</span>
require <span class="st">&#39;mongo&#39;</span>
require <span class="st">&#39;json&#39;</span></code></pre>
<p>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.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="dt">DB</span> = <span class="dt">Mongo</span>::<span class="dt">Connection</span>.new.db(<span class="st">&quot;mydb&quot;</span>, <span class="st">:pool_size</span> =&gt; <span class="dv">5</span>, <span class="st">:timeout</span> =&gt; <span class="dv">5</span>)</code></pre>
<p>Finally we define the routes to be supported by our API. Note that in the first two blocks - one for our application root (<code>/</code>) and the other for our todo items route <code>/todo</code> - we're using Haml for template rendering.</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby"><span class="kw">class</span> <span class="dt">TodoApp</span> &lt; <span class="dt">Sinatra</span>::<span class="dt">Base</span>
get <span class="st">&#39;/&#39;</span> <span class="kw">do</span>
haml <span class="st">:index</span>, <span class="st">:attr_wrapper</span> =&gt; <span class="st">&#39;&quot;&#39;</span>, <span class="st">:locals</span> =&gt; {<span class="st">:title</span> =&gt; <span class="st">&#39;hello&#39;</span>}
<span class="kw">end</span>
get <span class="st">&#39;/todo&#39;</span> <span class="kw">do</span>
haml <span class="st">:todo</span>, <span class="st">:attr_wrapper</span> =&gt; <span class="st">&#39;&quot;&#39;</span>, <span class="st">:locals</span> =&gt; {<span class="st">:title</span> =&gt; <span class="st">&#39;Our Sinatra Todo app&#39;</span>}
<span class="kw">end</span></code></pre>
<p><code>haml :index</code> instructs Sinatra to use the <code>views/index.haml</code> for the application index, whilst `<code>attr_wrapper</code> is simply defining the values to be used for any local variables defined inside the template. This similarly applies Todo items with the template `views/todo.haml'.</p>
<p>The rest of our routes make use of the <code>params</code> hash and a number of useful helper methods included with the MongoDB Ruby driver. For more details on these, please read the comments I've made inline below:</p>
<pre class="sourceCode ruby"><code class="sourceCode ruby">get <span class="st">&#39;/api/:thing&#39;</span> <span class="kw">do</span>
<span class="co"># query a collection :thing, convert the output to an array, map the _id </span>
<span class="co"># to a string representation of the object&#39;s _id and finally output to JSON</span>
<span class="dt">DB</span>.collection(params[<span class="st">:thing</span>]){|t| from_bson_id(t)}.to_json
<span class="kw">end</span>
get <span class="st">&#39;/api/:thing/:id&#39;</span> <span class="kw">do</span>
<span class="co"># get the first document with the id :id in the collection :thing as a single document (rather </span>
<span class="co"># than a Cursor, the standard output) using find_one(). Our bson utilities assist with</span>
<span class="co"># ID conversion and the final output returned is also JSON</span>
from_bson_id(<span class="dt">DB</span>.collection(params[<span class="st">:thing</span>]).find_one(to_bson_id(params[<span class="st">:id</span>]))).to_json
<span class="kw">end</span>
post <span class="st">&#39;/api/:thing&#39;</span> <span class="kw">do</span>
<span class="co"># parse the post body of the content being posted, convert to a string, insert into</span>
<span class="co"># the collection #thing and return the ObjectId as a string for reference</span>
oid = <span class="dt">DB</span>.collection(params[<span class="st">:thing</span>]).insert(<span class="dt">JSON</span>.parse(
<span class="st">&quot;{\&quot;_id\&quot;: \&quot;</span><span class="ot">#{</span>oid.to_s<span class="ot">}</span><span class="st">\&quot;}&quot;</span>
<span class="kw">end</span>
delete <span class="st">&#39;/api/:thing/:id&#39;</span> <span class="kw">do</span>
<span class="co"># remove the item with id :id from the collection :thing, based on the bson</span>
<span class="co"># representation of the object id</span>
<span class="dt">DB</span>.collection(params[<span class="st">:thing</span>]).remove(<span class="st">&#39;_id&#39;</span> =&gt; to_bson_id(params[<span class="st">:id</span>]))
<span class="kw">end</span>
put <span class="st">&#39;/api/:thing/:id&#39;</span> <span class="kw">do</span>
<span class="co"># collection.update() when used with $set (as covered earlier) allows us to set single values</span>
<span class="co"># in this case, the put request body is converted to a string, rejecting keys with the name &#39;_id&#39; for security purposes</span>
<span class="dt">DB</span>.collection(params[<span class="st">:thing</span>]).update({<span class="st">&#39;_id&#39;</span> =&gt; to_bson_id(params[<span class="st">:id</span>])}, {<span class="st">&#39;$set&#39;</span> =&gt; <span class="dt">JSON</span>.parse({|k,v| k == <span class="st">&#39;_id&#39;</span>}})
<span class="kw">end</span>
<span class="co"># utilities for generating/converting MongoDB ObjectIds</span>
<span class="kw">def</span> to_bson_id(id) <span class="dt">BSON</span>::<span class="dt">ObjectId</span>.from_string(id) <span class="kw">end</span>
<span class="kw">def</span> from_bson_id(obj) obj.merge({<span class="st">&#39;_id&#39;</span> =&gt; obj[<span class="st">&#39;_id&#39;</span>].to_s}) <span class="kw">end</span>
<span class="kw">end</span></code></pre>
<p>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.</p>
<p>For more on what MongoDB and the MongoDB Ruby driver are capable of, please do feel free to read their documentation for more information.</p>
<p>If you're a developer wishing to take this example further, why not try to add some additional capabilities to the service:</p>
<li>Validation: improved validation of data in the API. What more could be done to ensure data sanitization?</li>
<li>Search: search or filter down Todo items based on a set of keywords or within a certain date range</li>
<li>Pagination: only return the Nth number of Todo items or items from a start and end-point</li>
<h3 id="hamltemplates">Haml/Templates</h3>
<p>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.</p>
<p>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</p>
<p><code>/ These are templates</code></p>
<p>compiles to:</p>
<p><code>&lt;!-- These are templates --&gt;</code></p>
<h3 id="index.haml">index.haml</h3>
<pre class="sourceCode html"><code class="sourceCode html">%head
%meta{&#39;charset&#39; =&gt; &#39;utf-8&#39;}/
%meta{&#39;name&#39; =&gt; &#39;description&#39;, &#39;content&#39; =&gt; &#39;&#39;}/
%meta{&#39;name&#39; =&gt; &#39;author&#39;, &#39;content&#39; =&gt; &#39;&#39;}/
%meta{&#39;name&#39; =&gt; &#39;viewport&#39;, &#39;content&#39; =&gt; &#39;width=device-width,initial-scale=1&#39;}/
/ CSS concatenated and minified via ant build script
%link{&#39;rel&#39; =&gt; &#39;stylesheet&#39;, &#39;href&#39; =&gt; &#39;css/style.css&#39;}/
/ end CSS
%script{&#39;src&#39; =&gt; &#39;js/libs/modernizr.min.js&#39;}
= yield
/! end of #container
%script{&#39;src&#39; =&gt; &#39;;}
/ scripts concatenated and minified via ant build script
%script{&#39;src&#39; =&gt; &#39;js/mylibs/underscore.js&#39;}
%script{&#39;src&#39; =&gt; &#39;js/mylibs/backbone.js&#39;}
%script{&#39;defer&#39; =&gt; true, &#39;src&#39; =&gt; &#39;js/plugins.js&#39;}
%script{&#39;defer&#39; =&gt; true, &#39;src&#39; =&gt; &#39;js/script.js&#39;}
/ end scripts</code></pre>
<h3 id="todo.haml">todo.haml</h3>
<pre class="sourceCode html"><code class="sourceCode html">%div#todoapp
%input#new-todo{&quot;placeholder&quot; =&gt; &quot;What needs to be done?&quot;, &quot;type&quot; =&gt; &quot;text&quot;}/
%span.ui-tooltip-top{&quot;style&quot; =&gt; &quot;display:none;&quot;} Press Enter to save this task
/ Templates
%script#item-template{&quot;type&quot; =&gt; &quot;text/template&quot;}
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;todo </span><span class="er">&lt;</span><span class="st">%= done ? &#39;done&#39; : &#39;&#39; %&gt;&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;input</span><span class="ot"> class=</span><span class="st">&quot;check&quot;</span><span class="ot"> type=</span><span class="st">&quot;checkbox&quot;</span> <span class="er">&lt;%</span><span class="ot">=</span> <span class="st">done</span> <span class="st">?</span> <span class="er">&#39;checked</span><span class="ot">=</span><span class="st">&quot;checked&quot;</span><span class="er">&#39;</span><span class="ot"> :</span> <span class="er">&#39;&#39;</span> <span class="er">%</span><span class="kw">&gt;</span> /&gt;
%input.todo-input{&quot;type&quot; =&gt; &quot;text&quot;, &quot;value&quot; =&gt;&quot;&quot;}/
<span class="kw">&lt;/div&gt;</span>
%script#stats-template{&quot;type&quot; =&gt; &quot;text/template&quot;}
<span class="er">&lt;</span>% if (total) { %&gt;
%span.number <span class="er">&lt;</span>%= remaining %&gt;
%span.word <span class="er">&lt;</span>%= remaining == 1 ? &#39;item&#39; : &#39;items&#39; %&gt;
<span class="er">&lt;</span>% } %&gt;
<span class="er">&lt;</span>% if (done) { %&gt;
%a{&quot;href&quot; =&gt; &quot;#&quot;}
%span.number-done <span class="er">&lt;</span>%= done %&gt;
%span.word-done <span class="er">&lt;</span>%= done == 1 ? &#39;item&#39; : &#39;items&#39; %&gt;
<span class="er">&lt;</span>% } %&gt;</code></pre>
<h2 id="conclusions">Conclusions</h2>
<p>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 on-par with the effort required for the Node/Express implementation of the same application.</p>
<p>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.</p>
<h2 id="advanced"># <a name="advanced">Advanced</a></h2>
<h2 id="modular-javascript"><a name="modularjs">Modular JavaScript</a></h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<h2 id="organizing-modules-with-requirejs-and-amd"><a name="organizingmodules">Organizing modules with RequireJS and AMD</a></h2>
<p>In case you haven't used it before, <a href="">RequireJS</a> 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.</p>
<p>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:</p>
<ol style="list-style-type: decimal">
<li>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.</li>
<p>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.</p>
<ol start="2" style="list-style-type: decimal">
<li>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.</li>
<p>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.</p>
<p>I've previously written <a href="">a detailed article</a> 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.</p>
<h3 id="writing-amd-modules-with-requirejs">Writing AMD modules with RequireJS</h3>
<p>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 <code>define()</code> method for facilitating module definition and a <code>require()</code> method for handling dependency loading. <code>define()</code> is used to define named or unnamed modules based on the proposal using the following signature:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define(
module_id <span class="co">/*optional*/</span>,
[dependencies] <span class="co">/*optional*/</span>,
definition <span class="kw">function</span> <span class="co">/*function for instantiating the module or object*/</span>
<p>As you can tell by the inline comments, the <code>module_id</code> 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.</p>
<p>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 <code>define()</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// A module ID has been omitted here to make the module anonymous</span>
define([<span class="ch">&#39;foo&#39;</span>, <span class="ch">&#39;bar&#39;</span>],
<span class="co">// module definition function</span>
<span class="co">// dependencies (foo and bar) are mapped to function parameters</span>
<span class="kw">function</span> ( foo, bar ) {
<span class="co">// return a value that defines the module export</span>
<span class="co">// (i.e the functionality we want to expose for consumption)</span>
<span class="co">// create your module here</span>
<span class="kw">var</span> myModule = {
<span class="dt">doStuff</span>:<span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Yay! Stuff&#39;</span>);
<span class="kw">return</span> myModule;
<h4 id="alternate-syntax">Alternate syntax</h4>
<p>There is also a <a href="">sugared version</a> of <code>define()</code> available that allows you to declare your dependencies as local variables using <code>require()</code>. This will feel familiar to anyone who's used node, and can be easier to add or remove dependencies. Here is the previous snippet using the alternate syntax:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// A module ID has been omitted here to make the module anonymous</span>
define(<span class="kw">function</span>(require){
<span class="co">// module definition function</span>
<span class="co">// dependencies (foo and bar) are defined as local vars</span>
<span class="kw">var</span> foo = require(<span class="ch">&#39;foo&#39;</span>),
bar = require(<span class="ch">&#39;bar&#39;</span>);
<span class="co">// return a value that defines the module export</span>
<span class="co">// (i.e the functionality we want to expose for consumption)</span>
<span class="co">// create your module here</span>
<span class="kw">var</span> myModule = {
<span class="dt">doStuff</span>:<span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Yay! Stuff&#39;</span>);
<span class="kw">return</span> myModule;
<p>The <code>require()</code> 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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Consider &#39;foo&#39; and &#39;bar&#39; are two external modules</span>
<span class="co">// In this example, the &#39;exports&#39; from the two modules loaded are passed as</span>
<span class="co">// function arguments to the callback (foo and bar)</span>
<span class="co">// so that they can similarly be accessed</span>
require([<span class="ch">&#39;foo&#39;</span>, <span class="ch">&#39;bar&#39;</span>], <span class="kw">function</span> ( foo, bar ) {
<span class="co">// rest of your code here</span>
<span class="kw">foo</span>.<span class="fu">doSomething</span>();
<p><strong>Wrapping modules, views and other components with AMD</strong></p>
<p>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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([<span class="ch">&#39;underscore&#39;</span>, <span class="ch">&#39;backbone&#39;</span>], <span class="kw">function</span>(_, Backbone) {
<span class="kw">var</span> myModel = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default attributes </span>
<span class="dt">defaults</span>: {
<span class="dt">content</span>: <span class="st">&quot;hello world&quot;</span>,
<span class="co">// A dummy initialization method</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="dt">clear</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">destroy</span>();
<span class="kw">this</span>.<span class="fu">view</span>.<span class="fu">remove</span>();
<span class="kw">return</span> myModel;
<p>Note how we alias Underscore.js's instance to <code>_</code> and Backbone to just <code>Backbone</code>, 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:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">define([
<span class="ch">&#39;jquery&#39;</span>,
<span class="ch">