Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: c47f6dd36e
Fetching contributors…

Cannot retrieve contributors at this time

5955 lines (4193 sloc) 309.912 kb
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote {
margin: 0;
padding: 0;
}
body {
font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif;
font-size: 13px;
line-height: 18px;
color: #737373;
margin: 10px 13px 10px 13px;
}
a {
color: #0069d6;
}
a:hover {
color: #0050a3;
text-decoration: none;
}
a img {
border: none;
}
p {
margin-bottom: 9px;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #404040;
line-height: 36px;
}
h1 {
margin-bottom: 18px;
font-size: 30px;
}
h2 {
font-size: 24px;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
font-size: 13px;
}
hr {
margin: 0 0 19px;
border: 0;
border-bottom: 1px solid #ccc;
}
blockquote {
padding: 13px 13px 21px 15px;
margin-bottom: 18px;
font-family:georgia,serif;
font-style: italic;
}
blockquote:before {
content:"\201C";
font-size:40px;
margin-left:-10px;
font-family:georgia,serif;
color:#eee;
}
blockquote p {
font-size: 14px;
font-weight: 300;
line-height: 18px;
margin-bottom: 0;
font-style: italic;
}
code, pre {
font-family: Monaco, Andale Mono, Courier New, monospace;
}
code {
background-color: #fee9cc;
color: rgba(0, 0, 0, 0.75);
padding: 1px 3px;
font-size: 12px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
pre {
display: block;
padding: 14px;
margin: 0 0 18px;
line-height: 16px;
font-size: 11px;
border: 1px solid #d9d9d9;
white-space: pre-wrap;
word-wrap: break-word;
}
pre code {
background-color: #fff;
color:#737373;
font-size: 11px;
padding: 0;
}
@media screen and (min-width: 768px) {
body {
width: 748px;
margin:10px auto;
}
}
</style>
<title>Developing Backbone.js Applications</title>
</head>
<body>
<h1>Developing Backbone.js Applications</h1>
<h4>By Addy Osmani (<a href="http://twitter.com/addyosmani">@addyosmani</a>)</h4>
<hr />
<!-- sharing options for online version-->
<div style="width:500px">
<iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=addyosmani&repo=backbone-fundamentals&type=watch&count=true"
allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<a style="float:leftt" href="https://twitter.com/share" class="twitter-share-button" data-url="https://github.com/addyosmani/backbone-fundamentals" data-via="addy_osmani">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<p>&nbsp;</br></p>
</div>
<!-- end sharing-->
<h2>Prelude</h2>
<p>This is the home of &lsquo;Developing Backbone.js Applications&rsquo;, an (in-progress) book about the Backbone.js framework for structuring JavaScript applications. It is released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">license</a>.</p>
<p>I am quite pleased to announce that this book will be out in physical form in a few months time via <a href="http://oreilly.com">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 copy for free 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="https://github.com/addyosmani/backbone-fundamentals/contributors">these</a> members of the community for their assistance tweaking the project.</p>
<p>I hope you find this book helpful!</p>
<h2>Index</h2>
<ul>
<li><h4><a href="#introduction">Introduction</a></h4></li>
<li><h4><a href="#fundamentals">Fundamentals</a></h4>
<ul>
<li><a href="#mvc-mvp">MVC, MVP &amp; Backbone.js</a></li>
</ul>
</li>
<li><h4><a href="#thebasics">The Basics</a></h4>
<ul>
<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>
</ul>
</li>
<li><h4><a href="#restfulapps">RESTful Applications</a></h4>
<ul>
<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>
</ul>
</li>
<li><h4><a href="#advanced">Advanced</a></h4>
<ul>
<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>
</ul>
</li>
<li><h4><a href="#testing">Unit Testing</a></h4>
<ul>
<li><a href="#unittestingjasmine">Unit Testing Backbone Applications With Jasmine</a>
<ul>
<li>Introduction</li>
<li>Jasmine
<ul>
<li>Suites, Specs And Spies</li>
<li>TDD With Backbone
<ul>
<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>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#unittestingqunit">Unit Testing Backbone Applications With QUnit And SinonJS</a>
<ul>
<li>Introduction</li>
<li>QUnit
<ul>
<li>Assertions</li>
<li>Adding structure to assertions</li>
<li>Assertion examples</li>
<li>Fixtures</li>
<li>Asynchronous code</li>
</ul>
</li>
<li>SinonJS
<ul>
<li>Stubs</li>
<li>Mocks</li>
</ul>
</li>
<li>Practical
<ul>
<li>Testing Models</li>
<li>Testing Collections</li>
<li>Testing Views</li>
<li>Testing Events</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><h4><a href="#resources">Resources</a></h4></li>
</ul>
<h2><a name="introduction">Introduction</a></h2>
<hr />
<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&rsquo;t simply about how long a framework has been around. It&rsquo;s about how solid the framework is and more importantly how well it&rsquo;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&rsquo;s models, views, collections and routers. I&rsquo;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&rsquo;re still unsure whether or not to give it a try, why not take a look at how <a href="http://github.com/addyosmani/todomvc">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&rsquo;t take long and you&rsquo;ll be helping other developers avoid problems you&rsquo;ve run into before.</p>
<h2><a name="fundamentals">Fundamentals</a></h2>
<hr />
<p>In this section we are going to cover the context into which a framework like Backbone.js fits. Let&rsquo;s begin our journey into understanding Backbone better with a look at code architecture.</p>
<h3><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&rsquo;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&rsquo;re going to review two popular patterns - MVC and MVP. We&rsquo;ll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in.</p>
<h2>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="http://en.wikipedia.org/wiki/Trygve_Reenskaug">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="http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612">“Design Patterns: Elements of Reusable Object-Oriented Software”</a> (The &ldquo;GoF&rdquo; or “Gang of Four” book) in 1994, which played a role in popularizing its use.</p>
<h3>Smalltalk-80 MVC</h3>
<p>It&rsquo;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&rsquo;s, graphical user-interfaces were far and few between. An approach known as <a href="http://martinfowler.com/eaaDev/uiArchs.html">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&rsquo;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&rsquo;s MVC architecture:</p>
<ul>
<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&rsquo;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&rsquo;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>
</ul>
<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&rsquo;s architecture decades ago. In Smalltalk-80&rsquo;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="http://martinfowler.com/eaaDev/uiArchs.html">origins</a> of MVC over the years and if you are interested in further historical information about Smalltalk-80&rsquo;s MVC, I recommend reading his work.</p>
<h2>MVC As We Know It</h2>
<p>We&rsquo;ve reviewed the 70&rsquo;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 &ldquo;spaghetti&rdquo; code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let&rsquo;s look at what the MVC pattern enables the Javascript developer to do.</p>
<p>MVC is composed of three core components:</p>
<h3>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&rsquo;s an example of a simple Photo model implemented with Backbone.js:</p>
<pre><code>var Photo = Backbone.Model.extend({
// Default attributes for the photo
defaults: {
// Ensure that each photo created has an `src`.
src: "placeholder.jpg",
caption: "A default image",
viewed: false
},
initialize: function() {
}
});
</code></pre>
<p>The built-in capabilities of models vary across frameworks, however it&rsquo;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&rsquo;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&rsquo;t care how these views are organized, it simply announces updates to its data as necessary. We&rsquo;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 &ldquo;Collections&rdquo;. 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&rsquo;s how we might group Photo models into a simplified Backbone Collection:</p>
<pre><code>var PhotoGallery = Backbone.Collection.extend({
// Reference to this collection's model.
model: Photo,
// Filter down the list of all photos that have been viewed
viewed: function() {
return this.filter(function(photo){ return photo.get('viewed'); });
},
// Filter down the list to only photos that have not yet been viewed
unviewed: function() {
return this.without.apply(this, this.viewed());
}
});
</code></pre>
<p>If you read older texts on MVC, you may come across a description of models as also managing application &lsquo;state&rsquo;. In JavaScript applications &ldquo;state&rdquo; has a specific meaning, typically referring to the current &ldquo;state&rdquo; of a view or sub-view on a user&rsquo;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>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 &lsquo;dumb&rsquo;, 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 &ldquo;edit&rdquo; 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&rsquo;ll be covering shortly.</p>
<p>Let&rsquo;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&rsquo;s not the view&rsquo;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&rsquo;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><code>var buildPhotoView = function( photoModel, photoController ){
var base = document.createElement('div'),
photoEl = document.createElement('div');
base.appendChild(photoEl);
var render= function(){
// We use a templating library such as Underscore
// templating which generates the HTML for our
// photo entry
photoEl.innerHTML = _.template('photoTemplate', {src: photoModel.getSrc()});
}
photoModel.addSubscriber( render );
photoEl.addEventListener('click', function(){
photoController.handleEvent('click', photoModel );
});
var show = function(){
photoEl.style.display = '';
}
var hide = function(){
photoEl.style.display = 'none';
}
return{
showView: show,
hideView: hide
}
}
</code></pre>
<p><strong>Templating</strong></p>
<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 &lsquo;template&rsquo; 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 &lsquo;text/template&rsquo;). 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&rsquo;s compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore&rsquo;s &lsquo;microtemplates&rsquo;.</p>
<p><strong>Handlebars.js:</strong></p>
<pre><code>&lt;li class="photo"&gt;
&lt;h2&gt;{{caption}}&lt;/h2&gt;
&lt;img class="source" src="{{src}}"/&gt;
&lt;div class="meta-data"&gt;
{{metadata}}
&lt;/div&gt;
&lt;/li&gt;
</code></pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre><code>&lt;li class="photo"&gt;
&lt;h2&gt;&lt;%= caption %&gt;&lt;/h2&gt;
&lt;img class="source" src="&lt;%= src %&gt;"/&gt;
&lt;div class="meta-data"&gt;
&lt;%= metadata %&gt;
&lt;/div&gt;
&lt;/li&gt;
</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><code>_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
</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&rsquo;t automatically update the URL, the role of navigation thus falls to a &ldquo;router&rdquo;, 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>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&rsquo;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&rsquo;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 &ldquo;proper&rdquo; role of controllers in other non-Javascript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone&rsquo;s Views typically contain &ldquo;controller&rdquo; 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&rsquo;s in fact better to see it a member of the MV<em> 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</em> should you be relying on discussions of MVC to help with your Backbone projects.</p>
<h3>Controllers in Spine.js vs Backbone.js</h3>
<p><strong>Spine.js</strong></p>
<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&rsquo;t have its <strong>own</strong> explicit controllers, it&rsquo;s useful to review the controller from another MVC framework to appreciate the difference in implementations. Let&rsquo;s take a look at <a href="http://spinejs.com/">Spine.js</a>:</p>
<p>In this example, we&rsquo;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&rsquo;t be delving heavily into Spine.js beyond this example, but it&rsquo;s worth looking at it to learn more about Javascript frameworks in general.)</p>
<pre><code>// Controllers in Spine are created by inheriting from Spine.Controller
var PhotosController = Spine.Controller.sub({
init: function(){
this.item.bind("update", this.proxy(this.render));
this.item.bind("destroy", this.proxy(this.remove));
},
render: function(){
// Handle templating
this.replace($("#photoTemplate").tmpl(this.item));
return this;
},
remove: function(){
this.el.remove();
this.release();
}
});
</code></pre>
<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&rsquo;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&rsquo;re using this to render a JavaScript template called #photoTemplate which simply returns a HTML string used to replace the controller&rsquo;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><strong>Backbone.js</strong></p>
<p>Later on in this section we&rsquo;re going to revisit the differences between Backbone and traditional MVC, but for now let&rsquo;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&rsquo;s main purpose is to translate URL requests into application states. When a user browses to the URL www.example.com/photos/42, a Router could be used to show the photo with that ID, and to define what application behavior should be run in response to that request. Routers <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&rsquo;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><code>var PhotoRouter = Backbone.Router.extend({
routes: { "photos/:id": "route" },
route: function(id) {
var item = photoCollection.get(id);
var view = new PhotoView({ model: item });
something.html( view.render().el );
}
}):
</code></pre>
<h2>What does MVC give us?</h2>
<p>To summarize, the separation of concerns in MVC facilitates modularization of an application&rsquo;s functionality and enables:</p>
<ul>
<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.</li>
<li>Decoupling models and views means that it&rsquo;s straight-forward to write unit tests for business logic</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>
</ul>
<h3>Delving deeper</h3>
<p>Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we&rsquo;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 &ldquo;set of classes to build a user interface&rdquo;. In their view, it&rsquo;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&rsquo;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&rsquo;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&rsquo;t covered in many articles about the MVC pattern). When a model is changed it &ldquo;publishes&rdquo; to the rest of the application that it has been updated. The &ldquo;subscriber&rdquo;&ndash;generally a Controller&ndash;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>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&rsquo;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>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="http://en.wikipedia.org/wiki/Taligent">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>Models, Views &amp; Presenters</h3>
<p>The P in MVP stands for presenter. It&rsquo;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 &ldquo;dumb&rdquo;), 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&rsquo;s the presenter&rsquo;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&rsquo;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="http://martinfowler.com/eaaDev/PassiveScreen.html">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&rsquo;t have the interface construct in JavaScript, we&rsquo;re using it more as more a protocol than an explicit interface here. It&rsquo;s technically still an API and it&rsquo;s probably fair for us to refer to it as an interface from that perspective.</p>
<p>There is also a <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a> variation of MVP, which is closer to the MVC and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey&rsquo;s Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone.</p>
<h2>MVP or MVC?</h2>
<p>MVP is generally used most often in enterprise-level applications where it&rsquo;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&rsquo;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&rsquo;s quite a difference between opting for MVP for a JavaScript project over one for say, ASP.net).</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>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&rsquo;t view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.net or GWT). This is because it&rsquo;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="http://ireneros.com/">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>
<ul>
<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&rsquo;t that different from the classical MVC &ldquo;Model&rdquo;)</li>
<li>The views best represent templates (e.g Handlebars/Mustache markup templates)</li>
</ul>
<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&rsquo;re able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.</p>
<p>We&rsquo;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 &lsquo;subscribe&rsquo; to changes to a View&rsquo;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><code>var PhotoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Pass the contents of the photo template through a templating
// function, cache it for a single photo
template: _.template($('#photo-template').html()),
// The DOM events specific to an item.
events: {
"click img" : "toggleViewed"
},
// The PhotoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Photo** and a **PhotoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.model.bind('destroy', this.remove);
},
// Re-render the photo entry
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
// Toggle the `"viewed"` state of the model.
toggleViewed: function() {
this.model.viewed();
}
});
</code></pre>
<p>Another (quite different) opinion is that Backbone more closely resembles <a href="http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController">Smalltalk-80 MVC</a>, which we went through earlier.</p>
<p>As regular Backbone user Derick Bailey has <a href="http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/">written</a>, it&rsquo;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&rsquo;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>Fast facts</h2>
<h3>Backbone.js</h3>
<ul>
<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&rsquo;ll see, it&rsquo;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&rsquo;s <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/">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&rsquo;s micro-templating is available by default. Backbone works well with libraries like Handlebars</li>
<li>Doesn&rsquo;t support deeply nested models, though there are Backbone plugins such as <a href="https://github.com/PaulUithol/Backbone-relational">this</a> which can help</li>
<li>Clear and flexible conventions for structuring applications. Backbone doesn&rsquo;t force usage of all of its components and can work with only those needed.</li>
</ul>
<h2><a name="thebasics">The Basics</a></h2>
<hr />
<h3>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&rsquo;s my architectural framework of choice as it&rsquo;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&rsquo;s a level of comfort in knowing you&rsquo;re unlikely to run into issues which are either not explained in the official docs or which can&rsquo;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>Why should you consider using it?</h3>
<p>Backbone&rsquo;s main benefits, regardless of your target platform or device, include helping:</p>
<ul>
<li>Organize the structure to your application</li>
<li>Simplify server-side persistence</li>
<li>Decouple the DOM from your page&rsquo;s data</li>
<li>Model data, views and routers in a succinct manner</li>
<li>Provide DOM, model and collection synchronization</li>
</ul>
<h2>The Basics</h2>
<p>In this section, you&rsquo;ll learn the essentials of Backbone&rsquo;s models, views, collections and routers, as well as about using namespacing to organize your code. This isn&rsquo;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>
<ul>
<li>Models</li>
<li>Collections</li>
<li>Routers</li>
<li>Views</li>
<li>Namespacing</li>
</ul>
<h3><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><code>var Photo = Backbone.Model.extend({
defaults: {
src: 'placeholder.jpg',
title: 'an image placeholder',
coordinates: [0,0]
},
initialize: function(){
this.bind("change:src", function(){
var src = this.get("src");
console.log('Image source updated to ' + src);
});
},
changeSrc: function( source ){
this.set({ src: source });
}
});
var somePhoto = new Photo({ src: "test.jpg", title:"testing"});
somePhoto.changeSrc("magic.jpg"); // which triggers "change:src" and logs an update message to the console.
</code></pre>
<h4>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&rsquo;ll see why it&rsquo;s good practice to use it below.</p>
<pre><code>var Photo = Backbone.Model.extend({
initialize: function(){
console.log('this model has been initialized');
}
});
/*We can then create our own instance of a photo as follows:*/
var myPhoto = new Photo();
</code></pre>
<h4>Getters &amp; Setters</h4>
<p><strong>Model.get()</strong></p>
<p><code>Model.get()</code> provides easy access to a model&rsquo;s attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval.</p>
<pre><code>var myPhoto = new Photo({ title: "My awesome photo",
src:"boston.jpg",
location: "Boston",
tags:['the big game', 'vacation']}),
title = myPhoto.get("title"), //My awesome photo
location = myPhoto.get("location"), //Boston
tags = myPhoto.get("tags"), // ['the big game','vacation']
photoSrc = myPhoto.get("src"); //boston.jpg
</code></pre>
<p>Alternatively, if you wish to directly access all of the attributes in a model&rsquo;s instance directly, you can achieve this as follows:</p>
<pre><code>var myAttributes = myPhoto.attributes;
console.log(myAttributes);
</code></pre>
<p>It is best practice to use <code>Model.set()</code> or direct instantiation to set the values of a model&rsquo;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&rsquo;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><code>var myAttributes = myPhoto.toJSON();
console.log(myAttributes);
/* this returns { title: "My awesome photo",
src:"boston.jpg",
location: "Boston",
tags:['the big game', 'vacation']}*/
</code></pre>
<h4>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&rsquo;s important to avoid trying to set a Model&rsquo;s attributes directly (for example Model.caption = &lsquo;A new caption&rsquo;). Backbone uses Model.set() to know when to broadcast that a model&rsquo;s data has changed.</p>
<pre><code>var Photo = Backbone.Model.extend({
initialize: function(){
console.log('this model has been initialized');
}
});
/*Setting the value of attributes via instantiation*/
var myPhoto = new Photo({ title: 'My awesome photo', location: 'Boston' });
var myPhoto2 = new Photo();
/*Setting the value of attributes through Model.set()*/
myPhoto2.set({ title:'Vacation in Florida', location: 'Florida' });
</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&rsquo;t provided by the user). This can be set using a property called <code>defaults</code> in your model.</p>
<pre><code>var Photo = Backbone.Model.extend({
defaults:{
title: 'Another photo!',
tags: ['untagged'],
location: 'home',
src: 'placeholder.jpg'
},
initialize: function(){
}
});
var myPhoto = new Photo({ location: "Boston",
tags:['the big game', 'vacation']}),
title = myPhoto.get("title"), //Another photo!
location = myPhoto.get("location"), //Boston
tags = myPhoto.get("tags"), // ['the big game','vacation']
photoSrc = myPhoto.get("src"); //placeholder.jpg
</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><code>this.bind('change', function(){
console.log('values for this model have changed');
});
</code></pre>
<p>In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered.</p>
<pre><code>var Photo = Backbone.Model.extend({
defaults:{
title: 'Another photo!',
tags: ['untagged'],
location: 'home',
src: 'placeholder.jpg'
},
initialize: function(){
console.log('this model has been initialized');
this.bind("change:title", function(){
var title = this.get("title");
console.log("My title has been changed to.. " + title);
});
},
setTitle: function(newTitle){
this.set({ title: newTitle });
}
});
var myPhoto = new Photo({ title:"Fishing at the lake", src:"fishing.jpg"});
myPhoto.setTitle('Fishing at sea');
//logs My title has been changed to.. Fishing at sea
</code></pre>
<p><strong>Validation</strong></p>
<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><code>var Photo = Backbone.Model.extend({
validate: function(attribs){
if(attribs.src === undefined){
return "Remember to set a source for your image!";
}
},
initialize: function(){
console.log('this model has been initialized');
this.bind("error", function(model, error){
console.log(error);
});
}
});
var myPhoto = new Photo();
myPhoto.set({ title: "On the beach" });
//logs Remember to set a source for your image!
</code></pre>
<h3><a name="views">Views</a></h3>
<p>Views in Backbone don&rsquo;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&rsquo;s <code>render()</code> function can be bound to a model&rsquo;s <code>change()</code> event, allowing the view to always be up to date without requiring a full page refresh.</p>
<h4>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&rsquo;ll explain this code in detail below:</p>
<pre><code>var PhotoSearch = Backbone.View.extend({
el: $('#results'),
render: function( event ){
var compiled_template = _.template( $("#results-template").html() );
this.el.html( compiled_template(this.model.toJSON()) );
return this; //recommended as this enables calls to be chained.
},
events: {
"submit #searchForm": "search",
"click .reset": "reset",
"click .advanced": "switchContext"
},
search: function( event ){
//executed when a form '#searchForm' has been submitted
},
reset: function( event ){
//executed when an element with class "reset" has been clicked.
},
switchContext: function( event ){
//executed when an element with class "advanced" has been clicked.
}
});
</code></pre>
<h4>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><code>el: '#footer',
// OR
el: document.getElementById( 'footer' )
</code></pre>
<p>If you want to create a new element for you view, set any combination of the following view&rsquo;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: 'p', // required, but defaults to 'div' if not set
className: 'container', // optional, you can assign multiple classes to this property like so 'container homepage'
id: 'header', // optional
</code></pre>
<p>The above code creates the <code>DOMElement</code> below but doesn&rsquo;t append it to the DOM.</p>
<pre><code>&lt;p id="header" class="container"&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&rsquo;ll use Underscore&rsquo;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&rsquo;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>{"eventName selector": "callbackFunction"}</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&rsquo;t instantly obvious is that under the bonnet, Backbone uses jQuery&rsquo;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><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&rsquo;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><code>var PhotoCollection = Backbone.Collection.extend({
model: Photo
});
</code></pre>
<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><code>var skiingEpicness = PhotoCollection.get(2);
</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&rsquo;s client id from its <code>.cid</code> property.</p>
<pre><code>var mySkiingCrash = PhotoCollection.getByCid(456);
</code></pre>
<p>Backbone Collections don&rsquo;t have setters as such, but do support adding new models via <code>.add()</code> and removing models via <code>.remove()</code>.</p>
<pre><code>var a = new Backbone.Model({ title: 'my vacation'}),
b = new Backbone.Model({ title: 'my holiday'});
var photoCollection = new PhotoCollection([a,b]);
photoCollection.remove([a,b]);
</code></pre>
<p><strong>Listening for events</strong></p>
<p>As collections represent a group of items, we&rsquo;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&rsquo;s an example:</p>
<pre><code>var PhotoCollection = new Backbone.Collection();
PhotoCollection.bind("add", function(photo) {
console.log("I liked " + photo.get("title") + ' its this one, right? ' + photo.get("src"));
});
PhotoCollection.add([
{title: "My trip to Bali", src: "bali-trip.jpg"},
{title: "The flight home", src: "long-flight-oofta.jpg"},
{title: "Uploading pix", src: "too-many-pics.jpg"}
]);
</code></pre>
<p>In addition, we&rsquo;re able to bind a <code>change</code> event to listen for changes to models in the collection.</p>
<pre><code>PhotoCollection.bind("change:title", function(){
console.log('there have been updates made to this collections titles');
});
</code></pre>
<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&rsquo;s contents will be replaced with the contents of the array.</p>
<pre><code>var PhotoCollection = new Backbone.Collection;
PhotoCollection.url = '/photos';
PhotoCollection.fetch();
</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&rsquo;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><code>Backbone.sync = function(method, model) {
console.log("I've been passed " + method + " with " + JSON.stringify(model));
};
</code></pre>
<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><code>PhotoCollection.reset([
{title: "My trip to Scotland", src: "scotland-trip.jpg"},
{title: "The flight from Scotland", src: "long-flight.jpg"},
{title: "Latest snap of lock-ness", src: "lockness.jpg"}]);
</code></pre>
<h3>Underscore utility functions</h3>
<p>As Backbone requires Underscore as a hard dependency, we&rsquo;re able to use many of the utilities it has to offer to aid with our application development. Here&rsquo;s an example of how Underscore&rsquo;s <code>sortBy()</code> method can be used to sort a collection of photos based on a particular attribute.</p>
<pre><code>var sortedByAlphabet = PhotoCollection.sortBy(function (photo) {
return photo.get("title").toLowerCase();
});
</code></pre>
<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="http://documentcloud.github.com/underscore/">docs</a>.</p>
<h3><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&rsquo;s pushState and History API. Some examples of routes may be seen below:</p>
<pre><code>http://unicorns.com/#whatsup
http://unicorns.com/#search/seasonal-horns/page2
</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><code>"route" : "mappedFunction"
</code></pre>
<p>Let us now define our first controller by extending <code>Backbone.Router</code>. For the purposes of this guide, we&rsquo;re going to continue pretending we&rsquo;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><code>var GalleryRouter = Backbone.Router.extend({
/* define the route and function maps for this router */
routes: {
"about" : "showAbout",
/*Sample usage: http://unicorns.com/#about*/
"photos/:id" : "getPhoto",
/*This is an example of using a ":param" variable which allows us to match
any of the components between two URL slashes*/
/*Sample usage: http://unicorns.com/#photos/5*/
"search/:query" : "searchPhotos"
/*We can also define multiple routes that are bound to the same map function,
in this case searchPhotos(). Note below how we're optionally passing in a
reference to a page number if one is supplied*/
/*Sample usage: http://unicorns.com/#search/lolcats*/
"search/:query/p:page" : "searchPhotos",
/*As we can see, URLs may contain as many ":param"s as we wish*/
/*Sample usage: http://unicorns.com/#search/lolcats/p1*/
"photos/:id/download/*imagePath" : "downloadPhoto",
/*This is an example of using a *splat. splats are able to match any number of
URL components and can be combined with ":param"s*/
/*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/
/*If you wish to use splats for anything beyond default routing, it's probably a good
idea to leave them at the end of a URL otherwise you may need to apply regular
expression parsing on your fragment*/
"*other" : "defaultRoute"
/*This is a default route that also uses a *splat. Consider the
default route a wildcard for URLs that are either not matched or where
the user has incorrectly typed in a route path manually*/
/*Sample usage: http://unicorns.com/#anything*/
},
showAbout: function(){
},
getPhoto: function(id){
/*
Note that the id matched in the above route will be passed to this function
*/
console.log("You are trying to reach photo " + id);
},
searchPhotos: function(query, page){
console.log("Page number: " + page + " of the results for " + query);
},
downloadPhoto: function(id, path){
},
defaultRoute: function(other){
console.log("Invalid. You attempted to reach:" + other);
}
});
/* Now that we have a router setup, remember to instantiate it*/
var myGalleryRouter = new GalleryRouter();
</code></pre>
<p>As of Backbone 0.5+, it&rsquo;s possible to opt-in for HTML5 pushState support via <code>window.history.pushState</code>. This permits you to define routes such as http://www.scriptjunkie.com/just/an/example. This will be supported with automatic degradation when a user&rsquo;s browser doesn&rsquo;t support pushState. For the purposes of this tutorial, we&rsquo;ll use the hashtag method.</p>
<h4>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&rsquo;ve been accessed.</p>
<p>The <code>Backbone.history.start()</code> method will simply tell Backbone that it&rsquo;s OK to begin monitoring all <code>hashchange</code> events as follows:</p>
<pre><code>Backbone.history.start();
Router.navigate();
</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><code>/*Lets imagine we would like a specific fragment for when a user zooms into a photo*/
zoomPhoto: function(factor){
this.zoom(factor); //imagine this zooms into the image
this.navigate("zoom/" + factor); //updates the fragment for us, but doesn't trigger the route
}
</code></pre>
<p>It is also possible for <code>Router.navigate()</code> to trigger the route as well as updating the URL fragment.</p>
<pre><code>zoomPhoto: function(factor){
this.zoom(factor); //imagine this zooms into the image
this.navigate("zoom/" + factor, true); //updates the fragment for us and triggers the route
}
</code></pre>
<h3><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>What is namespacing?</h4>
<p>The basic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They&rsquo;re important as it&rsquo;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 &lsquo;citizen&rsquo; of the global namespace, it&rsquo;s also imperative that you do your best to similarly not prevent other developer&rsquo;s scripts executing due to the same issues.</p>
<p>JavaScript doesn&rsquo;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&rsquo;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&rsquo;ll be examining are:</p>
<ul>
<li>Single global variables</li>
<li>Object Literals</li>
<li>Nested namespacing</li>
</ul>
<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><code>var myApplication = (function(){
function(){
// ...
},
return {
// ...
}
})();
</code></pre>
<p>You&rsquo;ve probably seen this technique before. A Backbone-specific example might look like this:</p>
<pre><code>var myViews = (function(){
return {
PhotoView: Backbone.View.extend({ .. }),
GalleryView: Backbone.View.extend({ .. }),
AboutView: Backbone.View.extend({ .. });
//etc.
};
})();
</code></pre>
<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&rsquo;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><code>var myApplication_photoView = Backbone.View.extend({}),
myApplication_galleryView = Backbone.View.extend({});
</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&rsquo;s views about the single global variable pattern, read his <a href="http://michaux.ca/articles/javascript-namespacing">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&rsquo;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><code>/*Doesn't check for existence of myApplication*/
var myApplication = {};
/*
Does check for existence. If already defined, we use that instance.
Option 1: if(!myApplication) myApplication = {};
Option 2: var myApplication = myApplication || {};
We can then populate our object literal to support models, views and collections (or any data, really):
*/
var myApplication = {
models : {},
views : {
pages : {}
},
collections : {}
};
</code></pre>
<p>One can also opt for adding properties directly to the namespace (such as your views, in the following example):</p>
<pre><code>var myGalleryViews = myGalleryViews || {};
myGalleryViews.photoView = Backbone.View.extend({});
myGalleryViews.galleryView = Backbone.View.extend({});
</code></pre>
<p>The benefit of this pattern is that you&rsquo;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&rsquo;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&rsquo;s an example of a hypothetical object literal that stores application configuration settings:</p>
<pre><code>var myConfig = {
language: 'english',
defaults: {
enableGeolocation: true,
enableSharing: false,
maxPhotos: 20
},
theme: {
skin: 'a',
toolbars: {
index: 'ui-navigation-toolbar',
pages: 'ui-custom-toolbar'
}
}
}
</code></pre>
<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&rsquo;s <a href="http://blog.rebeccamurphey.com/2009/10/15/using-objects-to-organize-your-code">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&rsquo;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&rsquo;s unlikely the same nested children do. For example, Yahoo&rsquo;s YUI uses the nested object namespacing pattern extensively:</p>
<pre><code>YAHOO.util.Dom.getElementsByClassName('test');
</code></pre>
<p>Yahoo&rsquo;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><code>var galleryApp = galleryApp || {};
/*perform similar check for nested children*/
galleryApp.routers = galleryApp.routers || {};
galleryApp.model = galleryApp.model || {};
galleryApp.model.special = galleryApp.model.special || {};
/*routers*/
galleryApp.routers.Workspace = Backbone.Router.extend({});
galleryApp.routers.PhotoSearch = Backbone.Router.extend({});
/*models*/
galleryApp.model.Photo = Backbone.Model.extend({});
galleryApp.model.Comment = Backbone.Model.extend({});
/*special models*/
galleryApp.model.special.Admin = Backbone.Model.extend({});
</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&rsquo;s JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you&rsquo;re calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the &lsquo;nested&rsquo; approach to be quite negligible.</p>
<p><strong>Recommendation</strong></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&rsquo;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><a name="additional-tips">Additional Tips</a></h3>
<h4>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&rsquo;m happy to recommend checking out a tool called <a href="https://github.com/brunch/brunch">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&rsquo;ll be happy to know that there are Brunch bundles available for both.</p>
<h4>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&rsquo;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>Is Backbone too small for my application&rsquo;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&rsquo;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&rsquo;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&rsquo;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><a name="restfulapps">RESTful Applications</a></h2>
<hr />
<h2><a name="restful">Building RESTful applications with Backbone</a></h2>
<p>In this section of the book, we&rsquo;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&rsquo;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><a name="stack1">Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB</a></h2>
<p>The first stack we&rsquo;ll be looking at is:</p>
<ul>
<li><a href="nodejs.org">Node.js</a></li>
<li><a href="http://expressjs.com/">Express</a></li>
<li><a href="http://mongoosejs.com/">Mongoose</a></li>
<li>and <a href="http://www.mongodb.org/">MongoDB</a></li>
</ul>
<p>with <a href="http://jade-lang.com/">Jade</a> used optionally as a view/templating engine.</p>
<h3>Reviewing the stack</h3>
<p>As you may know, node.js is an event-driven platform (built on the <a href="http://code.google.com/apis/v8/design.html">V8</a> runtime), designed for writing fast, scalable network applications. It&rsquo;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="http://www.sinatrarb.com/">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="http://en.wikipedia.org/wiki/NoSQL">noSQL</a> database, rather than storing data in tables and rows (something we&rsquo;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="http://en.wikipedia.org/wiki/Relational_database">relational</a> databases (rich functionality).</p>
<p>Mongoose is a JavaScript library that simplifies how we interact with Mongo. Like Express, it&rsquo;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&rsquo;ll be looking at later). It&rsquo;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&rsquo;t for everyone, our practical will cover working both with and without it.</p>
<h3>Practical</h3>
<p>For this practical, we&rsquo;re going to once again look at extending the popular Backbone Todo application. Rather than relying on localStorage for data persistence, we&rsquo;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><strong>app.js</strong></p>
<p>(See <a href="https://github.com/addyosmani/backbone-boilerplates/blob/master/option2/app.js">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><code>var application_root = __dirname,
express = require("express"),
path = require("path"),
mongoose = require('mongoose');
</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&rsquo;ll be using to pass in our routes.</p>
<pre><code>var app = express.createServer();
</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&rsquo;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><code>mongoose.connect('mongodb://localhost/my_database');
</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&rsquo;s <code>text</code> content, its <code>done</code> state and <code>order</code> position in the overall Todo list.</p>
<pre><code>var Todo = mongoose.model('Todo', new mongoose.Schema({
text: String,
done: Boolean,
order: Number
}));
</code></pre>
<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><code>app.configure(function(){
// the bodyParser middleware parses JSON request bodies
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.set('views', path.join(application_root, "views"));
app.set('view engine', 'jade')
});
</code></pre>
<p>Should you prefer to switch out Jade for an alternative view engine, this can be done fairly trivially. See the section under &lsquo;Templating&rsquo; here:
https://github.com/joyent/node/wiki/modules. 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 &lsquo;/&rsquo;. As a trivial route in this application, it doesn&rsquo;t do anything particularly exciting, however getters typically read or retrieve data.</p>
<pre><code>app.get('/', function(req, res){
res.send('Hello World');
});
</code></pre>
<p>Onto something a little more useful and in our next route, navigating to &lsquo;/todo&rsquo; will actually render our Jade view &lsquo;todo.jade&rsquo;, as seen in the callback. Additional configuration values can be passed as the second parameter, such as the custom title specified below.</p>
<pre><code>app.get('/todo', function(req, res){
res.render('todo', {title: "Our sample application"});
});
</code></pre>
<p>Next, we can see the first of our &lsquo;/api/&rsquo; routes.</p>
<pre><code>app.get('/api/todos', function(req, res){
return Todo.find(function(err, todos) {
return res.send(todos);
});
});
</code></pre>
<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 &lsquo;/api/todos/:id&rsquo; 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><code>app.get('/api/todos/:id', function(req, res){
return Todo.findById(req.params.id, function(err, todo) {
if (!err) {
return res.send(todo);
}
});
});
</code></pre>
<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&rsquo;s three attributes (text, done, order) easily.</p>
<pre><code>app.put('/api/todos/:id', function(req, res){
return Todo.findById(req.params.id, function(err, todo) {
todo.text = req.body.text;
todo.done = req.body.done;
todo.order = req.body.order;
return todo.save(function(err) {
if (!err) {
console.log("updated");
}
return res.send(todo);
});
});
});
</code></pre>
<p>We&rsquo;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><code>app.post('/api/todos', function(req, res){
var todo;
todo = new Todo({
text: req.body.text,
done: req.body.done,
order: req.body.order
});
todo.save(function(err) {
if (!err) {
return console.log("created");
}
});
return res.send(todo);
});
</code></pre>
<p>We of course also want to support deleting todos (e.g if a todo has been &lsquo;cleared&rsquo;, it should be deleted). This also works based on a specific todo ID.</p>
<pre><code>app.delete('/api/todos/:id', function(req, res){
return Todo.findById(req.params.id, function(err, todo) {
return todo.remove(function(err) {
if (!err) {
console.log("removed");
return res.send('')
}
});
});
});
</code></pre>
<p>Finally, this last line is to ensure we&rsquo;re only listening on the port app.js is running.</p>
<pre><code>app.listen(3000);
</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&rsquo;ll find a version of the Backbone Todo app originally by Jerome Gravel-Niquet. Let&rsquo;s pay attention to <a href="https://github.com/addyosmani/backbone-boilerplates/blob/master/option2/public/js/script.js">script.js</a>. In order to change the application to work with our new back-end, we&rsquo;ll need to make some very minor changes to this.</p>
<p>Reviewing <code>window.TodoList</code> (a Backbone Collection), you&rsquo;ll notice that it has a property called <code>localStorage</code>, which uses the Backbone <a href="https://github.com/jeromegn/Backbone.localStorage">localStorage</a> adapter in order to facilitate storing data using the browser&rsquo;s localStorage features.</p>
<pre><code>window.TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
// Typically, this should be a unique name within your application
localStorage: new Store("todos"),
</code></pre>
<p>In order to switch it over to our RESTful backend, we&rsquo;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 &lsquo;/api/todos&rsquo;, this is the value we set <code>url</code> to.</p>
<pre><code> // localStorage: new Store("todos"),
url: '/api/todos',
</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><strong>todo.jade</strong></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&rsquo;s added.</p>
<pre>
// Todo App Interface
#todoapp
.title
h1 Todos
.content
#create-todo
input#new-todo(placeholder=&quot;What needs to be done?&quot;, type=&quot;text&quot;)
span.ui-tooltip-top(style=&quot;display:none;&quot;) Press Enter to save this task
#todos
ul#todo-list
#todo-stats
// Templates
script#item-template(type=&quot;text/template&quot;)
&lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
.display
&lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
.todo-text
span#todo-destroy
.edit
input.todo-input(type=&quot;text&quot;, &quot;value&quot;=&quot;&quot;)
&lt;/div&gt;
script#stats-template(type=&quot;text/template&quot;)
&lt;% if (total) { %&gt;
span.todo-count
span.number &lt;%= remaining %&gt;
span.word &lt;%= remaining == 1 ? 'item' : 'items' %&gt;
| left.
&lt;% } %&gt;
&lt;% if (done) { %&gt;
span.todo-clear
a(href=&quot;#&quot;)
| Clear
span.number-done &lt;%= done %&gt;
| completed
span.word-done &lt;%= done == 1 ? 'item' : 'items' %&gt;
&lt;% } %&gt;
</pre>
<p><strong>layout.jade</strong></p>
<pre>
!!! 5
//if lt IE 6
&lt;html class=&quot;no-js ie6 oldie&quot; lang=&quot;en&quot;&gt;
//if IE 7
&lt;html class=&quot;no-js ie7 oldie&quot; lang=&quot;en&quot;&gt;
//if IE 8
&lt;html class=&quot;no-js ie8 oldie&quot; lang=&quot;en&quot;&gt;
//if gt IE 8
&lt;!--&gt; &lt;html class=&quot;no-js&quot; lang=&quot;en&quot;&gt; &lt;!--
head
meta(charset=&quot;utf-8&quot;)
meta(http-equiv=&quot;X-UA-Compatible&quot;, content=&quot;IE=edge,chrome=1&quot;)
title=title
meta(name=&quot;description&quot;, content=&quot;&quot;)
meta(name=&quot;author&quot;, content=&quot;&quot;)
meta(name=&quot;viewport&quot;, content=&quot;width=device-width,initial-scale=1&quot;)
// CSS concatenated and minified via ant build script
link(rel=&quot;stylesheet&quot;, href=&quot;css/style.css&quot;)
// end CSS
script(src=&quot;js/libs/modernizr-2.0.6.min.js&quot;)
body
#container
header
#main(role=&quot;main&quot;)!=body
footer
//! end of #container
script(src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js&quot;)
script
window.jQuery || document.write('&lt;script src=&quot;js/libs/jquery-1.6.2.min.js&quot;&gt;&lt;\\/script&gt;')
// scripts concatenated and minified via ant build script
script(src=&quot;js/mylibs/underscore.js&quot;)
script(src=&quot;js/mylibs/backbone.js&quot;)
script(defer, src=&quot;js/plugins.js&quot;)
script(defer, src=&quot;js/script.js&quot;)
// end scripts
// Change UA-XXXXX-X to be your site's ID
script
window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
Modernizr.load({load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'});
//if lt IE 7
script(src=&quot;//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js&quot;)
script
window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})
&lt;/html&gt;
</pre>
<p><strong>static.html</strong></p>
<p>Alternatively, a static version of our index which doesn&rsquo;t rely on Jade can be put together as follows. See <a href="https://github.com/addyosmani/backbone-boilerplates/blob/master/option1/public/static.html">here</a> for the complete file or below for a sample.</p>
<pre>
&lt;div id=&quot;container&quot;&gt;
&lt;div id=&quot;main&quot; role=&quot;main&quot;&gt;
&lt;!-- Todo App Interface--&gt;
&lt;div id=&quot;todoapp&quot;&gt;
&lt;div class=&quot;title&quot;&gt;
&lt;h1&gt;Todos&lt;/h1&gt;
&lt;/div&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;div id=&quot;create-todo&quot;&gt;
&lt;input id=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; type=
&quot;text&quot; /&gt;&lt;span style=&quot;display:none;&quot; class=&quot;ui-tooltip-top&quot;&gt;Press Enter to
save this task&lt;/span&gt;
&lt;/div&gt;
&lt;div id=&quot;todos&quot;&gt;
&lt;ul id=&quot;todo-list&quot;&gt;&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&quot;todo-stats&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!-- Templates--&gt;
&lt;script id=&quot;item-template&quot; type=&quot;text/template&quot;&gt;
&lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
&lt;div class=&quot;display&quot;&gt;&lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
&lt;div class=&quot;todo-text&quot;&gt;&lt;/div&gt;&lt;span id=&quot;todo-destroy&quot;&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;edit&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; class=&quot;todo-input&quot;/&gt;&lt;/div&gt;&lt;/div&gt;
&lt;/script&gt;
&lt;script id=&quot;stats-template&quot; type=&quot;text/template&quot;&gt;
&lt;% if (total) { %&gt;
&lt;span class=&quot;todo-count&quot;&gt;&lt;span class=&quot;number&quot;&gt;&lt;%= remaining %&gt; &lt;/span&gt;&lt;span class=&quot;word&quot;&gt;&lt;%= remaining == 1 ? 'item' : 'items' %&gt;&lt;/span&gt; left.
&lt;/span&gt;&lt;% } %&gt;
&lt;% if (done) { %&gt;
&lt;span class=&quot;todo-clear&quot;&gt;&lt;a href=&quot;#&quot;&gt; Clear
&lt;span class=&quot;number-done&quot;&gt;&lt;%= done %&gt;&lt;/span&gt; completed
&lt;span class=&quot;word-done&quot;&gt;&lt;%= done == 1 ? 'item' : 'items' %&gt;&lt;/span&gt;&lt;/a&gt;&lt;/span&gt;&lt;% } %&gt;
&lt;/script&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!--! end of #container--&gt;
</pre>
<h3>Practical Setup</h3>
<p>We&rsquo;ve now gone through the major points of developing a RESTful backend using Node.js, Express and Mongoose. Next, let&rsquo;s make sure you can get your environment setup to run the updated Todo app.</p>
<h4>MongoDB</h4>
<p>Once you&rsquo;ve downloaded <a href="http://www.mongodb.org/downloads">MongoDB</a>, you&rsquo;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&rsquo;t actually create this directory for you. Navigate to where you&rsquo;ve downloaded and extracted MongoDB and run the following from terminal:</p>
<pre>
sudo mkdir -p /data/db/
sudo chown `id -u` /data/db
</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&rsquo;ll need to start <cpde>mongod`.</p>
<pre>
$ ./bin/mongod
</pre>
<p>Next, in the second terminal, start the `mongo&lt;/code shell which will connect up to localhost by default.</p>
<pre>
$ ./bin/mongo
</pre>
<p>That&rsquo;s it!.</p>
<h4>Express and Mongoose</h4>
<p>Option 1 (HTML) and Option 2 (Jade) of the practical download both come with an install.sh bash script. This allows you to easily install Express, Mongoose, Jade (and optionally MongoDB if you prefer to) through npm (the node package manager).</p>
<ul>
<li>Make sure you have Node.js installed. If not, you can grab it <a href="http://nodejs.org/#download">here</a></li>
<li>Next run <code>$ ./install.sh</code> at the terminal to install the rest of our dependencies. To see the exact contents of the install.sh file, see below:</li>
</ul>
<p><strong>install.sh</strong></p>
<pre>
#!/bin/bash
npm install express
npm install mongodb --mongodb:native
npm install mongoose
npm install jade
</pre>
<ul>
<li>After you&rsquo;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:</li>
</ul>
<pre>
git clone git://github.com/addyosmani/backbone-boilerplates.git
cd option2
node app.js
</pre>
<p>For option1 (without Jade), simply cd into option1 and run <code>node app.js</code> from there.</p>
<p>Finally, either of the example apps can now be accessed by navigating to:</p>
<ul>
<li>Option 1: <code>http://localhost:3000/static.html</code></li>
<li>Option 2: <code>http://localhost:3000/todo</code></li>
</ul>
<p>That&rsquo;s it! Whilst there&rsquo;s a lot more than can be done to expand on the concepts covered so far, the base we&rsquo;re reviewed should be enough to get you up and running with this stack if you wish to use it with Backbone.</p>
<h1><a name="stack2">Building Backbone.js Apps With Ruby, Sinatra, MongoDB and Haml</a></h1>
<h2>Introduction</h2>
<p>In this chapter we&rsquo;re going to explore writing Backbone.js applications with a Ruby back-end. To assist with this, we&rsquo;re going to use <a href="http://www.sinatrarb.com/">Sinatra</a> - a DSL (domain specific language) for rapidly creating web applications in Ruby. Similar to the <a href="https://github.com/addyosmani/backbone-fundamentals/#stack1">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>What Is Sinatra?</h2>
<p>In the past, you&rsquo;ve likely come across or used <a href="http://rubyonrails.org">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&rsquo;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&rsquo;s output as a response. Sinatra is particularly useful for getting projects up and running quickly where we don&rsquo;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>Getting Started With Sinatra</h2>
<p>Let&rsquo;s review how to write and run a very basic Sinatra application. As most programming languages and frameworks typically start with some variation of &ldquo;Hello World&rdquo;, we&rsquo;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>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><code>&amp;lt;a HTTP action&amp;gt; &amp;lt;the desired route&amp;gt; do
# some behaviour
end
</code></pre>
<p>A tiny route that outputs a &ldquo;Hello World&rdquo;-like message when we attempt to &ldquo;get&rdquo; the root could thus be written as follows:</p>
<pre><code>require 'sinatra'
get '/' do
"Hello World! Is it me you're looking for?"
end
</code></pre>
<p>To run this snippet, we can can simply save it to a local &lsquo;.rb&rsquo; file and execute it as follows:</p>
<pre><code>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&rsquo;t enforce much in the way of architectural structure, instead relying on simplicity to supporting writing powerful APIs.</p>
<p>Here&rsquo;s an example of a skeleton service we could put together supporting four common HTTP actions:</p>
<pre><code>get '/items' do
# list all items available
end
get '/item/:id' do
# get a single item
end
post '/item' do
# create a new item
end
put '/item/:id' do
# update an existing item
end
delete '/item/:id' do
# delete an item
end
</code></pre>
<p>Sinatra&rsquo;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><code>get '/item/:id' do
# this matches "GET /item/10" and "GET /item/11"
# params[:id] is "10" or "11"
"You reached #{params[:id]}"
end
</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="http://www.sinatrarb.com/documentation">docs</a>. Let&rsquo;s now take a look at handlers.</p>
<p>Sinatra includes convenient handler methods for tasks such as redirection, halting and passing.</p>
<h4>Redirection</h4>
<p>A simple route supporting redirection which returns a 302 response can be written as follows:</p>
<pre><code>get '/items' do
redirect '/items/welcome'
end
</code></pre>
<p>And if we wish to pass additional parameters such as arguments we can do so like this:
redirect &lsquo;http://site.com/&rsquo;, &lsquo;Oops! I think we have a problem!&rsquo;</p>
<h4>Halting</h4>
<p>To immediately stop a request (halting) we can use &lsquo;halt&rsquo;. Heres an example of halting a request where we specify the message body:</p>
<p><code>halt "who goes there!?"</code></p>
<h4>Passing</h4>
<p>&lsquo;Passing&rsquo; 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><code>get '/members/:username' do
pass unless params[:username] == 'rick-astley'
'Never gonna give you up, never gonna let you down'
end
get '/member/*' do
'Welcome!'
end
</code></pre>
<p>There are also handler methods that can assist with sessions (specifically, cookie-based session handling). To use Sinatra&rsquo;s session handling, first enable it in your application with:</p>
<pre><code>enable :sessions
</code></pre>
<p>You can then use the session handling capabilities as follows:</p>
<pre><code>get '/items' do
session['visitCounter'] ||= 0;
session['visitCounter'] += 1;
"This page has been accessed #{session['visitCounter']} times"
end
</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="http://www.sinatrarb.com/intro#Using%20Sessions">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>Templating And HAML</h2>
<p>Let&rsquo;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><code>get '/items' do
erb :default
# renders views/default.erb
end
</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><code>&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;%= data %&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
</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>
<ul>
<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>
</ul>
<p>For the purpose of comparison, below we can see an ERB template compared to it&rsquo;s Haml equivalent.</p>
<h4>ERB</h4>
<pre>
&lt;div class=&quot;todo&quot; id=&quot;content&quot;&gt;
&lt;h2 class=&quot;entry_title&quot;&gt;&lt;%= h @todo.title %&gt;&lt;/h2&gt;
&lt;div class=&quot;entry_link&quot;&gt;&lt;%= link_to('link', @todo.link) %&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<h4>Haml</h4>
<pre><code>.todo#content
%h2.entry_title= @todo.title
.entry_link= link_to('link', @todo.link)
</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&rsquo;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&rsquo;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&rsquo;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><code>%h1 This is some h1 text
%h2 This is some h2 text.
%p Now we have a line containing a single instance variable: @content
%p= @content
%p Embedding Ruby code in the middle of a line can be done using ==.
%p== Here is an example: #{@foobar}
%p We can also add attributes using {}
%p{:style =&gt; "color:green"} We just made this paragraph green!
%p You'll want to apply classes and ids to your DOM, too.
%p.foo This has the foo class
%p.bar This has the bar class
%p#foobar This has the foobar id
%p.foo#foobar Or you can combine them!
%p Nesting can be done like this
%p
Or even like this
</code></pre>
<p>Note: Haml is whitespace sensitive and will not correctly work if it isn&rsquo;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>MongoDB Ruby Driver</h1>
<h2>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&rsquo;re using the default port we can then connect as follows:</p>
<pre><code>require 'mongo'
# where 'learning-mongo' is the name of our database:
db = Connection.new.db('learning-mongo');
</code></pre>
<p>We probably also want to place some data into &lsquo;learning-mongo&rsquo;. It could be as simple as a note, so why don&rsquo;t we go ahead and begin a notes collection?:</p>
<pre><code>notes = db.collection('notes')
</code></pre>
<p>Something interesting worth noting is that at this point, we haven&rsquo;t actually created the database nor the collection we&rsquo;re referencing above.</p>
<p>Neither of these items exist in Mongo (just yet) but as we&rsquo;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 &lsquo;learning-mongo&rsquo; using <code>collection.insert()</code>:</p>
<pre><code>our_note = { :text =&gt; 'Remember the milk', :remindInterval =&gt; 'weekly'}
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><code>note = notes.find( :id =&gt; note_id ).first
</code></pre>
<p>This can also be used in conjunction with Mongo&rsquo;s <code>collection.update()</code> method and <a href="http://www.mongodb.org/display/DOCS/Updating">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><code>note = notes.find( :id =&gt; note_id ).first
note[:text] = 'Remember the bread'
notes.update({ :_id =&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><code>notes.update({ :_id =&gt; note_id }, '$set' =&gt; { :text = &gt; 'Remember the bread' })
</code></pre>
<p>Useful to know: Almost each MongoDB document has an _id field as it&rsquo;s first attribute. This can normally
be of any type, however a special BSON datatype is provided for object ids. It&rsquo;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="http://datamapper.org/why.html">project page</a>. <a href="http://sinatra-book.gittr.com/#datamapper">Sinatra: The Book</a> also contains a brief tutorial on DataMapper for anyone interested in exploring it further.</p>
<h1>Practical</h1>
<p>We&rsquo;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&rsquo;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&rsquo;t a great deal of changes needed to switch over to using our Sinatra-based API. Let&rsquo;s briefly review the code that will be powering the CRUD operations for this sections practical, as we go course won&rsquo;t be starting off with a near-complete base for most of our real world applications.</p>
<h3><a id="preq">Installing The Prerequisites</a></h3>
<h4>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&rsquo;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 http://www.ruby-lang.org/en/downloads/. Alternatively, (RVM)[http://beginrescueend.com/rvm/install/] (Ruby Version Manager) is a command-line tool that allows you to easily install and manage multiple ruby environments with ease.</p>
<h4>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&rsquo;s possible to install additional dependencies for Ruby applications very easily.</p>
<p>On OSX, Linux or Windows go to <a href="http://rubyforge.org/projects/rubygems">http://rubyforge.org/projects/rubygems</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>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&rsquo;re on Windows, enter the following at a command prompt:</p>
<p><code>c:\\ &gt; gem install sinatra</code></p>
<h4>Haml</h4>
<p>As with other DSLs and frameworks, Sinatra supports a wide range of different templating engines. <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html">ERB</a> is the one most often recommended by the Sinatra camp, however
as a part of this chapter, we&rsquo;re going to explore the use of <a href="http://haml.hamptoncatlin.com/">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>MongoDB</h4>
<p>If you haven&rsquo;t already downloaded and installed MongoDB from an earlier chapter, please <a href="http://www.mongodb.org/downloads">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>1.Data directories</h5>
<p>MongoDB stores data in the bin/data/db folder but won&rsquo;t actually create this directory for you. Navigate to where you&rsquo;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>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&rsquo;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>MongoDB Ruby Driver</h4>
<p>As we&rsquo;ll be using the <a href="https://github.com/mongodb/mongo-ruby-driver">MongoDB Ruby Driver</a>, we&rsquo;ll also require the following gems:</p>
<p>The gem for the driver itself:
<code>
$ gem install mongo
</code></p>
<p>and the driver&rsquo;s other prerequisite, bson:
<code>
$ gem install bson_ext
</code></p>
<p>This is basically a collection of extensions used to increase serialization speed.</p>
<p>That&rsquo;s it for our prerequisites!.</p>
<h2>Tutorial</h2>
<p>To get started, let&rsquo;s get a local copy of the practical application working on our system.</p>
<h3>Application Files</h3>
<p>Clone <a href="http://github.com/addyosmani/backbone-fundamentals">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>
<pre><code>--public
----css
----img
----js
-----script.js
----test
--views
app.rb
</code></pre>
<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>
<pre><code>--Models
----Todo
--Collections
----TodoList
--Views
---TodoView
---AppView
</code></pre>
<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&rsquo;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>Backbone</h3>
<h4>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><code>// Our overall **AppView** is the top-level piece of UI.
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"keyup #new-todo": "showTooltip",
"click .todo-clear a": "clearCompleted"
},
// At initialization
initialize: function() {
this.input = this.$("#new-todo");
Todos.on('add', this.addOne, this);
Todos.on('reset', this.addAll, this);
Todos.on('all', this.render, this);
Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done:
….
</code></pre>
<h3>Collections</h3>
<p>In the TodoList collection below, we&rsquo;ve set the <code>url</code> property to point to <code>/api/todos</code> to reference the collection&rsquo;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&rsquo;ll take a look at this again when writing the Ruby code powering our backend.</p>
<pre><code> // Todo Collection
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
// localStorage: new Store("todos"),
url: '/api/todos',
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function(todo) {
return todo.get('order');
}
});
</code></pre>
<h3>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><code>
// Our basic **Todo** model has `text`, `order`, and `done` attributes.
var Todo = Backbone.Model.extend({
idAttribute: "_id",
// Default attributes for a todo item.
defaults: function() {
return {
done: false,
order: Todos.nextOrder()
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});
</code></pre>
<h3>Ruby/Sinatra</h3>
<p>Now that we&rsquo;ve defined our main models, views and collections let&rsquo;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>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><code>require 'rubygems'
require 'sinatra'
require 'mongo'
require 'json'
</code></pre>
<p>Next, we create a new connection to Mongo, specifying any custom configuration desired. If running a multi-threaded application, setting the &lsquo;pool_size&rsquo; allows us to specify a maximum pool size and &lsquo;timeout&rsquo; a maximum timeout for waiting for old connections to be released to the pool.</p>
<pre><code>DB = Mongo::Connection.new.db("mydb", :pool_size =&gt; 5, :timeout =&gt; 5)
</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&rsquo;re using Haml for template rendering.</p>
<pre><code>class TodoApp &lt; Sinatra::Base
get '/' do
haml :index, :attr_wrapper =&gt; '"', :locals =&gt; {:title =&gt; 'hello'}
end
get '/todo' do
haml :todo, :attr_wrapper =&gt; '"', :locals =&gt; {:title =&gt; 'Our Sinatra Todo app'}
end
</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&rsquo;ve made inline below:</p>
<pre><code>get '/api/:thing' do
# query a collection :thing, convert the output to an array, map the _id
# to a string representation of the object's _id and finally output to JSON
DB.collection(params[:thing]).find.to_a.map{|t| from_bson_id(t)}.to_json
end
get '/api/:thing/:id' do
# get the first document with the id :id in the collection :thing as a single document (rather
# than a Cursor, the standard output) using find_one(). Our bson utilities assist with
# ID conversion and the final output returned is also JSON
from_bson_id(DB.collection(params[:thing]).find_one(to_bson_id(params[:id]))).to_json
end
post '/api/:thing' do
# parse the post body of the content being posted, convert to a string, insert into
# the collection #thing and return the ObjectId as a string for reference
oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.to_s))
"{\"_id\": \"#{oid.to_s}\"}"
end
delete '/api/:thing/:id' do
# remove the item with id :id from the collection :thing, based on the bson
# representation of the object id
DB.collection(params[:thing]).remove('_id' =&gt; to_bson_id(params[:id]))
end
put '/api/:thing/:id' do
# collection.update() when used with $set (as covered earlier) allows us to set single values
# in this case, the put request body is converted to a string, rejecting keys with the name '_id' for security purposes
DB.collection(params[:thing]).update({'_id' =&gt; to_bson_id(params[:id])}, {'$set' =&gt; JSON.parse(request.body.read.to_s).reject{|k,v| k == '_id'}})
end
# utilities for generating/converting MongoDB ObjectIds
def to_bson_id(id) BSON::ObjectId.from_string(id) end
def from_bson_id(obj) obj.merge({'_id' =&gt; obj['_id'].to_s}) end
end
</code></pre>
<p>That&rsquo;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&rsquo;re a developer wishing to take this example further, why not try to add some additional capabilities to the service:</p>
<ul>
<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>
</ul>
<h3>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&rsquo;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>index.haml</h3>
<pre><code>%head
%meta{'charset' =&amp;gt; 'utf-8'}/
%title=title
%meta{'name' =&amp;gt; 'description', 'content' =&amp;gt; ''}/
%meta{'name' =&amp;gt; 'author', 'content' =&amp;gt; ''}/
%meta{'name' =&amp;gt; 'viewport', 'content' =&amp;gt; 'width=device-width,initial-scale=1'}/
/ CSS concatenated and minified via ant build script
%link{'rel' =&amp;gt; 'stylesheet', 'href' =&amp;gt; 'css/style.css'}/
/ end CSS
%script{'src' =&amp;gt; 'js/libs/modernizr.min.js'}
%body
%div#container
%header
%div#main
= yield
%footer
/! end of #container
%script{'src' =&amp;gt; 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'}
/ scripts concatenated and minified via ant build script
%script{'src' =&amp;gt; 'js/mylibs/underscore.js'}
%script{'src' =&amp;gt; 'js/mylibs/backbone.js'}
%script{'defer' =&amp;gt; true, 'src' =&amp;gt; 'js/plugins.js'}
%script{'defer' =&amp;gt; true, 'src' =&amp;gt; 'js/script.js'}
/ end scripts
</code></pre>
<h3>todo.haml</h3>
<pre><code>%div#todoapp
%div.title
%h1
Todos
%div.content
%div#create-todo
%input#new-todo{&amp;quot;placeholder&amp;quot; =&amp;gt; &amp;quot;What needs to be done?&amp;quot;, &amp;quot;type&amp;quot; =&amp;gt; &amp;quot;text&amp;quot;}/
%span.ui-tooltip-top{&amp;quot;style&amp;quot; =&amp;gt; &amp;quot;display:none;&amp;quot;} Press Enter to save this task
%div#todos
%ul#todo-list
%div#todo-stats
/ Templates
%script#item-template{&amp;quot;type&amp;quot; =&amp;gt; &amp;quot;text/template&amp;quot;}
&amp;lt;div class=&amp;quot;todo &amp;lt;%= done ? 'done' : '' %&amp;gt;&amp;quot;&amp;gt;
%div.display
&amp;lt;input class=&amp;quot;check&amp;quot; type=&amp;quot;checkbox&amp;quot; &amp;lt;%= done ? 'checked=&amp;quot;checked&amp;quot;' : '' %&amp;gt; /&amp;gt;
%div.todo-text
%span#todo-destroy
%div.edit
%input.todo-input{&amp;quot;type&amp;quot; =&amp;gt; &amp;quot;text&amp;quot;, &amp;quot;value&amp;quot; =&amp;gt;&amp;quot;&amp;quot;}/
&amp;lt;/div&amp;gt;
%script#stats-template{&amp;quot;type&amp;quot; =&amp;gt; &amp;quot;text/template&amp;quot;}
&amp;lt;% if (total) { %&amp;gt;
%span.todo-count
%span.number &amp;lt;%= remaining %&amp;gt;
%span.word &amp;lt;%= remaining == 1 ? 'item' : 'items' %&amp;gt;
left.
&amp;lt;% } %&amp;gt;
&amp;lt;% if (done) { %&amp;gt;
%span.todo-clear
%a{&amp;quot;href&amp;quot; =&amp;gt; &amp;quot;#&amp;quot;}
Clear
%span.number-done &amp;lt;%= done %&amp;gt;
completed
%span.word-done &amp;lt;%= done == 1 ? 'item' : 'items' %&amp;gt;
&amp;lt;% } %&amp;gt;
</code></pre>
<h2>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>
<h1><a name="advanced">Advanced</a></h1>
<hr />
<h2><a name="modularjs">Modular JavaScript</a></h2>
<p>When we say an application is modular, we generally mean it&rsquo;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&rsquo;t provide developers with the means to import such modules of code in a clean, organized manner. It&rsquo;s one of the concerns with specifications that haven&rsquo;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&rsquo;s still possible to incur naming collisions in your architecture. There&rsquo;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&rsquo;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><a name="organizingmodules">Organizing modules with RequireJS and AMD</a></h2>
<p>In case you haven&rsquo;t used it before, <a href="http://requirejs.org">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&rsquo;ll discuss more shortly. Some of RequireJS&rsquo;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>
<p>1) Backbone doesn&rsquo;t endorse a particular approach to modular-development. Although this means it&rsquo;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&rsquo;t sure of what works best when other concerns come into play, such as dependency management.</p>
<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 &lsquo;write lots of script tags with implicit dependencies and manage them manually&rsquo; 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>
<p>2) Let&rsquo;s discuss dependency management a little more as it can actually be quite challenging to get right if you&rsquo;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.</p>
<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 &lsquo;expand&rsquo;) 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&rsquo;ve previously written <a href="http://addyosmani.com/writing-modular-js">a detailed article</a> covering both AMD and other module formats and script loaders in case you&rsquo;d like to explore this topic further. The takeaway is that although it&rsquo;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>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><code>define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);
</code></pre>
<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&rsquo;s useful too). When this argument is left out, we call the module &lsquo;anonymous&rsquo;. When working with anonymous modules, the idea of a module&rsquo;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 (&lsquo;definition function&rsquo;) is a function that&rsquo;s executed to instantiate your module. A barebone module (compatible with RequireJS) could be defined using <code>define()</code> as follows:</p>
<pre><code>// A module ID has been omitted here to make the module anonymous
define(['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});
</code></pre>
<h4>Alternate syntax</h4>
<p>There is also a <a href="http://requirejs.org/docs/whyamd.html#sugar">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&rsquo;s used node, and can be easier to add or remove dependencies.
Here is the previous snippet using the alternate syntax:</p>
<pre><code>// A module ID has been omitted here to make the module anonymous
define(function(require){
// module definition function
// dependencies (foo and bar) are defined as local vars
var foo = require('foo'),
bar = require('bar');
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});
</code></pre>
<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><code>// Consider 'foo' and 'bar' are two external modules
// In this example, the 'exports' from the two modules loaded are passed as
// function arguments to the callback (foo and bar)
// so that they can similarly be accessed
require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});
</code></pre>
<p><strong>Wrapping modules, views and other components with AMD</strong></p>
<p>Now that we&rsquo;ve taken a look at how to define AMD modules, let&rsquo;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&rsquo;s simplest, a Backbone model may just require Backbone and Underscore.js. These are considered it&rsquo;s dependencies and so, to write an AMD model module, we would simply do this:</p>
<pre><code>define(['underscore', 'backbone'], function(_, Backbone) {
var myModel = Backbone.Model.extend({
// Default attributes
defaults: {
content: "hello world",
},
// A dummy initialization method
initialize: function() {
},
clear: function() {
this.destroy();
this.view.remove();
}
});
return myModel;
});
</code></pre>
<p>Note how we alias Underscore.js&rsquo;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><code>define([
'jquery',
'underscore',
'backbone',
'collections/mycollection',
'views/myview'
], function($, _, Backbone, myCollection, myView){
var AppView = Backbone.View.extend({
...
</code></pre>
<p>Aliasing to the dollar-sign (<code>$</code>), once again makes it very easy to encapsulate any part of an application you wish using AMD.</p>
<h2><a name="externaltemplates">Keeping Your Templates External Using RequireJS And The Text Plugin</a></h2>
<p>Moving your [Underscore/Mustache/Handlebars] templates to external files is actually quite straight-forward. As this application makes use of RequireJS, I&rsquo;ll discuss how to implement external templates using this specific script loader.</p>
<p>RequireJS has a special plugin called text.js which is used to load in text file dependencies. To use the text plugin, simply follow these simple steps:</p>
<ol>
<li><p>Download the plugin from http://requirejs.org/docs/download.html#text and place it in either the same directory as your application&rsquo;s main JS file or a suitable sub-directory.</p></li>
<li><p>Next, include the text.js plugin in your initial RequireJS configuration options. In the code snippet below, we assume that RequireJS is being included in our page prior to this code snippet being executed. Any of the other scripts being loaded are just there for the sake of example.</p></li>
</ol>
<pre><code>require.config( {
paths: {
'backbone': 'libs/AMDbackbone-0.5.3',
'underscore': 'libs/underscore-1.2.2',
'text': 'libs/require/text',
'jquery': 'libs/jQuery-1.7.1',
'json2': 'libs/json2',
'datepicker': 'libs/jQuery.ui.datepicker',
'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
'jquerymobile': 'libs/jquery.mobile-1.0'
},
baseUrl: 'app'
} );
</code></pre>
<ol>
<li>When the <code>text!</code> prefix is used for a dependency, RequireJS will automatically load the text plugin and treat the dependency as a text resource. A typical example of this in action may look like..</li>
</ol>
<pre><code>require(['js/app', 'text!templates/mainView.html'],
function(app, mainView){
// the contents of the mainView file will be
// loaded into mainView for usage.
}
);
</code></pre>
<ol>
<li>Finally we can use the text resource that&rsquo;s been loaded for templating purposes. You&rsquo;re probably used to storing your HTML templates inline using a script with a specific identifier.</li>
</ol>
<p>With Underscore.js&rsquo;s micro-templating (and jQuery) this would typically be:</p>
<p>HTML:</p>
<pre><code>&lt;script type="text/template" id="mainViewTemplate"&gt;
&lt;% _.each( person, function( person_item ){ %&gt;
&lt;li&gt;&lt;%= person_item.get("name") %&gt;&lt;/li&gt;
&lt;% }); %&gt;
&lt;/script&gt;
</code></pre>
<p>JS:</p>
<pre><code>var compiled_template = _.template( $('#mainViewTemplate').html() );
</code></pre>
<p>With RequireJS and the text plugin however, it&rsquo;s as simple as saving your template into an external text file (say, <code>mainView.html</code>) and doing the following:</p>
<pre><code>require(['js/app', 'text!templates/mainView.html'],
function(app, mainView){
var compiled_template = _.template( mainView );
}
);
</code></pre>
<p>That&rsquo;s it!. You can then go applying your template to a view in Backbone doing something like:</p>
<pre><code>collection.someview.el.html( compiled_template( { results: collection.models } ) );
</code></pre>
<p>All templating solutions will have their own custom methods for handling template compilation, but if you understand the above, substituting Underscore&rsquo;s micro-templating for any other solution should be fairly trivial.</p>
<p><strong>Note:</strong> You may also be interested in looking at <a href="https://github.com/ZeeAgency/requirejs-tpl">Require.js tpl</a>. It&rsquo;s an AMD-compatible version of the Underscore templating system that also includes support for optimization (pre-compiled templates) which can lead to better performance and no evals. I have yet to use it myself, but it comes as a recommended resource.</p>
<h2><a name="optimizingrequirejs">Optimizing Backbone apps for production with the RequireJS Optimizer</a></h2>
<p>As experienced developers may know, an essential final step when writing both small and large JavaScript web applications is the build process. The majority of non-trivial apps are likely to consist of more than one or two scripts and so optimizing, minimizing and concatenating your scripts prior to pushing them to production will require your users to download a reduced number (if not just one) script file.</p>
<p>Note: If you haven&rsquo;t looked at build processes before and this is your first time hearing about them, you might find <a href="http://addyosmani.com/blog/client-side-build-process/">my post and screencast on this topic</a> useful.</p>
<p>With some other structural JavaScript frameworks, my recommendation would normally be to implicitly use YUI Compressor or Google&rsquo;s closure compiler tools, but we have a slightly more elegant method available, when it comes to Backbone if you&rsquo;re using RequireJS. RequireJS has a command line optimization tool called r.js which has a number of capabilities, including:</p>
<ul>
<li>Concatenating specific scripts and minifying them using external tools such as UglifyJS (which is used by default) or Google&rsquo;s Closure Compiler for optimal browser delivery, whilst preserving the ability to dynamically load modules</li>
<li>Optimizing CSS and stylesheets by inlining CSS files imported using @import, stripping out comments etc.</li>
<li>The ability to run AMD projects in both Node and Rhino (more on this later)</li>
</ul>
<p>You&rsquo;ll notice that I mentioned the word &lsquo;specific&rsquo; in the first bullet point. The RequireJS optimizer only concatenates module scripts that have been specified in arrays of string literals passed to top-level (i.e non-local) require and define calls. As clarified by the <a href="http://requirejs.org/docs/optimization.html">optimizer docs</a> this means that Backbone modules defined like this:</p>
<pre><code>define(['jquery','backbone','underscore', 'collections/sample','views/test'],
function($,Backbone, _, Sample, Test){
//...
});
</code></pre>
<p>will combine fine, however inline dependencies such as:</p>
<pre><code>var models = someCondition ? ['models/ab','models/ac'] : ['models/ba','models/bc'];
</code></pre>
<p>will be ignored. This is by design as it ensures that dynamic dependency/module loading can still take place even after optimization.</p>
<p>Although the RequireJS optimizer works fine in both Node and Java environments, it&rsquo;s strongly recommended to run it under Node as it executes significantly faster there. In my experience, it&rsquo;s a piece of cake to get setup with either environment, so go for whichever you feel most comfortable with.</p>
<p>To get started with r.js, grab it from the <a href="http://requirejs.org/docs/download.html#rjs">RequireJS download page</a> or <a href="http://requirejs.org/docs/optimization.html#download">through NPM</a>. Now, the RequireJS optimizer works absolutely fine for single script and CSS files, but for most cases you&rsquo;ll want to actually optimize an entire Backbone project. You <em>could</em> do this completely from the command-line, but a cleaner option is using build profiles.</p>
<p>Below is an example of a build file taken from the modular jQuery Mobile app referenced later in this book. A <strong>build profile</strong> (commonly named <code>app.build.js</code>) informs RequireJS to copy all of the content of <code>appDir</code> to a directory defined by <code>dir</code> (in this case <code>../release</code>). This will apply all of the necessary optimizations inside the release folder. The <code>baseUrl</code> is used to resolve the paths for your modules. It should ideally be relative to <code>appDir</code>.</p>
<p>Near the bottom of this sample file, you&rsquo;ll see an array called <code>modules</code>. This is where you specify the module names you wish to have optimized. In this case we&rsquo;re optimizing the main application called &lsquo;app&rsquo;, which maps to <code>appDir/app.js</code>. If we had set the <code>baseUrl</code> to &lsquo;scripts&rsquo;, it would be mapped to <code>appDir/scripts/app.js</code>.</p>
<pre><code>({
appDir: "./",
baseUrl: "./",
dir: "../release",
paths: {
'backbone': 'libs/AMDbackbone-0.5.3',
'underscore': 'libs/underscore-1.2.2',
'jquery': 'libs/jQuery-1.7.1',
'json2': 'libs/json2',
'datepicker': 'libs/jQuery.ui.datepicker',
'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
'jquerymobile': 'libs/jquery.mobile-1.0'
},
optimize: "uglify",
modules: [
{
name: "app",
exclude: [
// If you prefer not to include certain libs exclude them here
]
}
]
})
</code></pre>
<p>The way the build system in r.js works is that it traverses app.js (whatever modules you&rsquo;ve passed) and resolved dependencies, concatenating them into the final <code>release</code>(dir) folder. CSS is treated the same way.</p>
<p>The build profile is usually placed inside the &lsquo;scripts&rsquo; or &lsquo;js&rsquo; directory of your project. As per the docs, this file can however exist anywhere you wish, but you&rsquo;ll need to edit the contents of your build profile accordingly.</p>
<p>Finally, to run the build, execute the following command once inside your <code>appDir</code> or <code>appDir/scripts</code> directory:</p>
<pre><code>node ../../r.js -o app.build.js
</code></pre>
<p>That&rsquo;s it. As long as you have UglifyJS/Closure tools setup correctly, r.js should be able to easily optimize your entire Backbone project in just a few key-strokes. If you would like to learn more about build profiles, James Burke has a <a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js">heavily commented sample file</a> with all the possible options available.</p>
<h2><a name="practicalrequirejs">Practical: Building a modular Backbone app with AMD &amp; RequireJS</a></h2>
<p>In this chapter, we&rsquo;ll look at our first practical Backbone &amp; RequireJS project - how to build a modular Todo application. The application will allow us to add new todos, edit new todos and clear todo items that have been marked as completed. For a more advanced practical, see the section on mobile Backbone development.</p>
<p>The complete code for the application can can be found in the <code>practicals/modular-todo-app</code> folder of this repo (thanks to Thomas Davis and J&eacute;r&ocirc;me Gravel-Niquet). Alternatively grab a copy of my side-project <a href="https://github.com/addyosmani/todomvc">TodoMVC</a> which contains the sources to both AMD and non-AMD versions.</p>
<p><strong>Note:</strong> Thomas may be covering a practical on this exercise in more detail on <a href="http://backbonetutorials.com">backbonetutorials.com</a> at some point soon, but for this section I&rsquo;ll be covering what I consider the core concepts.</p>
<h3>Overview</h3>
<p>Writing a &lsquo;modular&rsquo; Backbone application can be a straight-forward process. There are however, some key conceptual differences to be aware of if opting to use AMD as your module format of choice:</p>
<ul>
<li>As AMD isn&rsquo;t a standard native to JavaScript or the browser, it&rsquo;s necessary to use a script loader (such as RequireJS or curl.js) in order to support defining components and modules using this module format. As we&rsquo;ve already reviewed, there are a number of advantages to using the AMD as well as RequireJS to assist here.</li>
<li>Models, views, controllers and routers need to be encapsulated <em>using</em> the AMD-format. This allows each component of our Backbone application to cleanly manage dependencies (e.g collections required by a view) in the same way that AMD allows non-Backbone modules to.</li>
<li>Non-Backbone components/modules (such as utilities or application helpers) can also be encapsulated using AMD. I encourage you to try developing these modules in such a way that they can both be used and tested independent of your Backbone code as this will increase their ability to be re-used elsewhere.</li>
</ul>
<p>Now that we&rsquo;ve reviewed the basics, let&rsquo;s take a look at developing our application. For reference, the structure of our app is as follows:</p>
<pre>
index.html
...js/
main.js
.../models
todo.js
.../views
app.js
todos.js
.../collections
todos.js
.../templates
stats.html
todos.html
../libs
.../backbone
.../jquery
.../underscore
.../require
require.js
text.js
...css/
</pre>
<h3>Markup</h3>
<p>The markup for the application is relatively simple and consists of three primary parts: an input section for entering new todo items (<code>create-todo</code>), a list section to display existing items (which can also be edited in-place) (<code>todo-list</code>) and finally a section summarizing how many items are left to be completed (<code>todo-stats</code>).</p>
<pre>
&lt;div id=&quot;todoapp&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;div id=&quot;create-todo&quot;&gt;
&lt;input id=&quot;new-todo&quot; placeholder=&quot;What needs to be done?&quot; type=&quot;text&quot; /&gt;
&lt;span class=&quot;ui-tooltip-top&quot;&gt;Press Enter to save this task&lt;/span&gt;
&lt;/div&gt;
&lt;div id=&quot;todos&quot;&gt;
&lt;ul id=&quot;todo-list&quot;&gt;&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&quot;todo-stats&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The rest of the tutorial will now focus on the JavaScript side of the practical.</p>
<h3>Configuration options</h3>
<p>If you&rsquo;ve read the earlier chapter on AMD, you may have noticed that explicitly needing to define each dependency a Backbone module (view, collection or other module) may require with it can get a little tedious. This can however be improved.</p>
<p>In order to simplify referencing common paths the modules in our application may use, we use a RequireJS <a href="http://requirejs.org/docs/api.html#config">configuration object</a>, which is typically defined as a top-level script file. Configuration objects have a number of useful capabilities, the most useful being mode name-mapping. Name-maps are basically a key:value pair, where the key defines the alias you wish to use for a path and the value represents the true location of the path.</p>
<p>In the code-sample below, you can see some typical examples of common name-maps which include: <code>backbone</code>, <code>underscore</code>, <code>jquery</code> and depending on your choice, the RequireJS <code>text</code> plugin, which assists with loading text assets like templates.</p>
<p><strong>main.js</strong></p>
<pre><code>require.config({
baseUrl:'../',
paths: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-optamd3-min',
text: 'libs/require/text'
}
});
require(['views/app'], function(AppView){
var app_view = new AppView;
});
</code></pre>
<p>The <code>require()</code> at the end of our main.js file is simply there so we can load and instantiation the primary view for our application (<code>views/app.js</code>). You&rsquo;ll commonly see both this and the configuration object included the most top-level script file for a project.</p>
<p>In addition to offering name-mapping, the configuration object can be used to define additional properties such as <code>waitSeconds</code> - the number of seconds to wait before script loading times out and <code>locale</code>, should you wish to load up i18n bundles for custom languages. The <code>baseUrl</code> is simply the path to use for module lookups.</p>
<p>For more information on configuration objects, please feel free to check out the excellent guide to them in the <a href="http://requirejs.org/docs/api.html#config">RequireJS docs</a>.</p>
<h3>Modularizing our models, views and collections</h3>
<p>Before we dive into AMD-wrapped versions of our Backbone components, let&rsquo;s review a sample of a non-AMD view. The following view listens for changes to its model (a Todo item) and re-renders if a user edits the value of the item.</p>
<pre><code>var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick div.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter"
},
// The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.bind('change', this.render, this);
this.model.view = this;
},
...
</code></pre>
<p>Note how for templating the common practice of referencing a script by an ID (or other selector) and obtaining its value is used. This of course requires that the template being accessed is implicitly defined in our markup. The following is the &lsquo;embedded&rsquo; version of our template being referenced above:</p>
<pre>
&lt;script type=&quot;text/template&quot; id=&quot;item-template&quot;&gt;
&lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
&lt;div class=&quot;display&quot;&gt;
&lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
&lt;div class=&quot;todo-content&quot;&gt;&lt;/div&gt;
&lt;span class=&quot;todo-destroy&quot;&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;edit&quot;&gt;
&lt;input class=&quot;todo-input&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/script&gt;
</pre>
<p>Whilst there is nothing wrong with the template itself, once we begin to develop larger applications requiring multiple templates, including them all in our markup on page-load can quickly become both unmanageable and come with performance costs. We&rsquo;ll look at solving this problem in a minute.</p>
<p>Let&rsquo;s now take a look at the AMD-version of our view. As discussed earlier, the &lsquo;module&rsquo; is wrapped using AMD&rsquo;s <code>define()</code> which allows us to specify the dependencies our view requires. Using the mapped paths to &lsquo;jquery&rsquo; etc. simplifies referencing common dependencies and instances of dependencies are themselves mapped to local variables that we can access (e.g &lsquo;jquery&rsquo; is mapped to <code>$</code>).</p>
<p><strong>views/todos.js</strong></p>
<pre><code>define([
'jquery',
'underscore',
'backbone',
'text!templates/todos.html'
], function($, _, Backbone, todosTemplate){
var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template(todosTemplate),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick div.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter"
},
// The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.bind('change', this.render, this);
this.model.view = this;
},
// Re-render the contents of the todo item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.setContent();
return this;
},
// Use `jQuery.text` to set the contents of the todo item.
setContent: function() {
var content = this.model.get('content');
this.$('.todo-content').text(content);
this.input = this.$('.todo-input');
this.input.bind('blur', this.close);
this.input.val(content);
},
...
</code></pre>
<p> From a maintenance perspective, there&rsquo;s nothing logically different in this version of our view, except for how we approach templating.</p>
<p>Using the RequireJS text plugin (the dependency marked <code>text</code>), we can actually store all of the contents for the template we looked at earlier in an external file (todos.html).</p>
<p><strong>templates/todos.html</strong></p>
<pre>
&lt;div class=&quot;todo &lt;%= done ? 'done' : '' %&gt;&quot;&gt;
&lt;div class=&quot;display&quot;&gt;
&lt;input class=&quot;check&quot; type=&quot;checkbox&quot; &lt;%= done ? 'checked=&quot;checked&quot;' : '' %&gt; /&gt;
&lt;div class=&quot;todo-content&quot;&gt;&lt;/div&gt;
&lt;span class=&quot;todo-destroy&quot;&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;edit&quot;&gt;
&lt;input class=&quot;todo-input&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>There&rsquo;s no longer a need to be concerned with IDs for the template as we can map it&rsquo;s contents to a local variable (in this case <code>todosTemplate</code>). We then simply pass this to the Underscore.js templating function <code>_.template()</code> the same way we normally would have the value of our template script.</p>
<p>Next, let&rsquo;s look at how to define models as dependencies which can be pulled into collections. Here&rsquo;s an AMD-compatible model module, which has two default values: a <code>content</code> attribute for the content of a Todo item and a boolean <code>done</code> state, allowing us to trigger whether the item has been completed or not.</p>
<p><strong>models/todo.js</strong></p>
<pre><code>define(['underscore', 'backbone'], function(_, Backbone) {
var TodoModel = Backbone.Model.extend({
// Default attributes for the todo.
defaults: {
// Ensure that each todo created has `content`.
content: "empty todo...",
done: false
},
initialize: function() {
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
},
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
this.view.remove();
}
});
return TodoModel;
});
</code></pre>
<p>As per other types of dependencies, we can easily map our model module to a local variable (in this case <code>Todo</code>) so it can be referenced as the model to use for our <code>TodosCollection</code>. This collection also supports a simple <code>done()</code> filter for narrowing down Todo items that have been completed and a <code>remaining()</code> filter for those that are still outstanding.</p>
<p><strong>collections/todos.js</strong></p>
<pre><code>define([
'underscore',
'backbone',
'libs/backbone/localstorage',
'models/todo'
], function(_, Backbone, Store, Todo){
var TodosCollection = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos"),
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
},
...
</code></pre>
<p>In addition to allowing users to add new Todo items from views (which we then insert as models in a collection), we ideally also want to be able to display how many items have been completed and how many are remaining. We&rsquo;ve already defined filters that can provide us this information in the above collection, so let&rsquo;s use them in our main application view.</p>
<p><strong>views/app.js</strong></p>
<pre><code>define([
'jquery',
'underscore',
'backbone',
'collections/todos',
'views/todos',
'text!templates/stats.html'
], function($, _, Backbone, Todos, TodoView, statsTemplate){
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template(statsTemplate),
// ...events, initialize() etc. can be seen in the complete file
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var done = Todos.done().length;
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done: Todos.done().length,
remaining: Todos.remaining().length
}));
},
...
</code></pre>
<p>Above, we map the second template for this project, <code>templates/stats.html</code> to <code>statsTemplate</code> which is used for rendering the overall <code>done</code> and <code>remaining</code> states. This works by simply passing our template the length of our overall Todos collection (<code>Todos.length</code> - the number of Todo items created so far) and similarly the length (counts) for items that have been completed (<code>Todos.done().length</code>) or are remaining (<code>Todos.remaining().length</code>).</p>
<p>The contents of our <code>statsTemplate</code> can be seen below. It&rsquo;s nothing too complicated, but does use ternary conditions to evaluate whether we should state there&rsquo;s &ldquo;1 item&rdquo; or &ldquo;2 item<i>s</i>&rdquo; in a particular state.</p>
<pre>
&lt;% if (total) { %&gt;
&lt;span class=&quot;todo-count&quot;&gt;
&lt;span class=&quot;number&quot;&gt;&lt;%= remaining %&gt;&lt;/span&gt;
&lt;span class=&quot;word&quot;&gt;&lt;%= remaining == 1 ? 'item' : 'items' %&gt;&lt;/span&gt; left.
&lt;/span&gt;
&lt;% } %&gt;
&lt;% if (done) { %&gt;
&lt;span class=&quot;todo-clear&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
Clear &lt;span class=&quot;number-done&quot;&gt;&lt;%= done %&gt;&lt;/span&gt;
completed &lt;span class=&quot;word-done&quot;&gt;&lt;%= done == 1 ? 'item' : 'items' %&gt;&lt;/span&gt;
&lt;/a&gt;
&lt;/span&gt;
&lt;% } %&gt;
</pre>
<p>The rest of the source for the Todo app mainly consists of code for handling user and application events, but that rounds up most of the core concepts for this practical.</p>
<p>To see how everything ties together, feel free to grab the source by cloning this repo or browse it <a href="https://github.com/addyosmani/backbone-fundamentals/tree/master/practicals/modular-todo-app">online</a> to learn more. I hope you find it helpful!.</p>
<p><strong>Note:</strong> While this first practical doesn&rsquo;t use a build profile as outlined in the chapter on using the RequireJS optimizer, we will be using one in the section on building mobile Backbone applications.</p>
<h2><a name="decouplingbackbone">Decoupling Backbone with the Mediator and Facade patterns</a></h2>
<p>In this section we&rsquo;ll discuss applying some of the concepts I cover in my article on <a href="http://addyosmani.com/largescalejavascript">Large-scale JavaScript Application development</a> to Backbone.</p>
<h3>Summary</h3>
<p>At a high-level, one architecture that works for such applications is something which is:</p>
<ul>
<li><strong>Highly decoupled</strong>: encouraging modules to only publish and subscribe to events of interest rather than directly communicating with each other. This helps us to build applications who&rsquo;s units of code aren&rsquo;t highly tied (coupled) together and can thus be reused more easily.</li>
<li><strong>Supports module-level security</strong>: whereby modules are only able to execute behavior they&rsquo;ve been permitted to. Application security is an area which is often overlooked in JavaScript applications, but can be quite easily implemented in a flexible manner.</li>
<li><strong>Supports failover</strong>: allowing an application continuing to function even if particular modules fail. The typical example I give of this is the GMail chat widget. Imagine being able to build applications in a way that if one widget on the page fails (e.g chat), the rest of your application (mail) can continue to function without being affected.</li>
</ul>
<p>This is an architecture which has been implemented by a number of different companies in the past, including Yahoo! (for their modularized homepage - which Nicholas Zakas has <a href="http://www.youtube.com/watch?v=vXjVFPosQHw">spoken</a> about) and AOL for some of our upcoming projects.</p>
<p>The three design patterns that make this architecture possible are the:</p>
<ul>
<li><strong>Module pattern</strong>: used for encapsulating unique blocks of code, where functions and variables can be kept either public or private. (&lsquo;private&rsquo; in the simulation of privacy sense, as of course don&rsquo;t have true privacy in JavaScript)</li>
<li><strong>Mediator pattern</strong>: used when the communication between modules may be complex, but is still well defined. If it appears a system may have too many relationships between modules in your code, it may be time to have a central point of control, which is where the pattern fits in.</li>
<li><strong>Facade pattern</strong>: used for providing a convenient higher-level interface to a larger body of code, hiding its true underlying complexity</li>
</ul>
<p>Their specific roles in this architecture can be found below.</p>
<ul>
<li><strong>Modules</strong>: There are almost two concepts of what defines a module. As AMD is being used as a module wrapper, technically each model, view and collection can be considered a module. We then have the concept of modules being distinct blocks of code outside of just MVC/MV*. For the latter, these types of &lsquo;modules&rsquo; are primarily concerned with broadcasting and subscribing to events of interest rather than directly communicating with each other.They are made possible through the Mediator pattern.</li>
<li><strong>Mediator</strong>: The mediator has a varying role depending on just how you wish to implement it. In my article, I mention using it as a module manager with the ability to start and stop modules at will, however when it comes to Backbone, I feel that simplifying it down to the role of a central &lsquo;controller&rsquo; that provides pub/sub capabilities should suffice. One can of course go all out in terms of building a module system that supports module starting, stopping, pausing etc, however the scope of this is outside of this chapter.</li>
<li><strong>Facade</strong>: This acts as a secure middle-layer that both abstracts an application core (Mediator) and relays messages from the modules back to the Mediator so they don&rsquo;t touch it directly. The Facade also performs the duty of application security guard; it checks event notifications from modules against a configuration (permissions.js, which we will look at later) to ensure requests from modules are only processed if they are permitted to execute the behavior passed.</li>
</ul>
<p>For ease of reference, I sometimes refer to these three patterns grouped together as Aura (a word that means subtle, luminous light).</p>
<h3>Practical</h3>
<p>For the practical section of this chapter, we&rsquo;ll be extending the well-known Backbone Todo application using the three patterns mentioned above. The complete code for this section can be found here: https://github.com/addyosmani/backbone-aura and should ideally be run on at minimum, a local HTTP server.</p>
<p>The application is broken down into AMD modules that cover everything from Backbone models through to application-level modules. The views publish events of interest to the rest of the application and modules can then subscribe to these event notifications.</p>
<p>All subscriptions from modules go through a facade (or sandbox). What this does is check against the subscriber name and the &lsquo;channel/notification&rsquo; it&rsquo;s attempting to subscribe to. If a channel <em>doesn&rsquo;t</em> have permissions to be subscribed to (something established through permissions.js), the subscription isn&rsquo;t permitted.</p>
<p><strong>Mediator</strong></p>
<p>Found in <code>aura/mediator.js</code></p>
<p>Below is a very simple AMD-wrapped implementation of the mediator pattern, based on prior work by Ryan Florence. It accepts as it&rsquo;s input an object, to which it attaches <code>publish()</code> and <code>subscribe()</code> methods. In a larger application, the mediator can contain additional utilities, such as handlers for initializing, starting and stopping modules, but for demonstration purposes, these two methods should work fine for our needs.</p>
<pre><code>define([], function(obj){
var channels = {};
if (!obj) obj = {};
obj.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
obj.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i &lt; l; i++) {
channels[channel][i].apply(this, args);
}
};
return obj;
});
</code></pre>
<p><strong>Facade</strong></p>
<p>Found in <code>aura/facade.js</code></p>
<p>Next, we have an implementation of the facade pattern. Now the classical facade pattern applied to JavaScript would probably look a little like this:</p>
<pre><code>
var module = (function() {
var _private = {
i:5,
get : function() {
console.log('current value:' + this.i);
},
set : function( val ) {
this.i = val;
},
run : function() {
console.log('running');
},
jump: function(){
console.log('jumping');
}
};
return {
facade : function( args ) {
_private.set(args.val);
_private.get();
if ( args.run ) {
_private.run();
}
}
}
}());
module.facade({run: true, val:10});
//outputs current value: 10, running
</code></pre>
<p>It&rsquo;s effectively a variation of the module pattern, where instead of simply returning an interface of supported methods, your API can completely hide the true implementation powering it, returning something simpler. This allows the logic being performed in the background to be as complex as necessary, whilst all the end-user experiences is a simplified API they pass options to (note how in our case, a single method abstraction is exposed). This is a beautiful way of providing APIs that can be easily consumed.</p>
<p>That said, to keep things simple, our implementation of an AMD-compatible facade will act a little more like a proxy. Modules will communicate directly through the facade to access the mediator&rsquo;s <code>publish()</code> and <code>subscribe()</code> methods, however, they won&rsquo;t as such touch the mediator directly.This enables the facade to provide application-level validation of any subscriptions and publications made.</p>
<p>It also allows us to implement a simple, but flexible, permissions checker (as seen below) which will validate subscriptions made against a permissions configuration to see whether it&rsquo;s permitted or not.</p>
<pre><code>define([ "../aura/mediator" , "../aura/permissions" ], function (mediator, permissions) {
var facade = facade || {};
facade.subscribe = function(subscriber, channel, callback){
// Note: Handling permissions/security is optional here
// The permissions check can be removed
// to just use the mediator directly.
if(permissions.validate(subscriber, channel)){
mediator.subscribe( channel, callback );
}
}
facade.publish = function(channel){
mediator.publish( channel );
}
return facade;
});
</code></pre>
<p><strong>Permissions</strong></p>
<p>Found in <code>aura/permissions.js</code></p>
<p>In our simple permissions configuration, we support checking against subscription requests to establish whether they are allowed to clear. This enforces a flexible security layer for the application.</p>
<p>To visually see how this works, consider changing say, permissions -> renderDone -> todoCounter to be false. This will completely disable the application from from rendering or displaying the counts component for Todo items left (because they aren&rsquo;t allowed to subscribe to that event notification). The rest of the Todo app can still however be used without issue.</p>
<p>It&rsquo;s a very dumbed down example of the potential for application security, but imagine how powerful this might be in a large app with a significant number of visual widgets.</p>
<pre><code>define([], function () {
// Permissions
// A permissions structure can support checking
// against subscriptions prior to allowing them
// to clear. This enforces a flexible security
// layer for your application.
var permissions = {
newContentAvailable: {
contentUpdater:true
},
endContentEditing:{
todoSaver:true
},
beginContentEditing:{
editFocus:true
},
addingNewTodo:{
todoTooltip:true
},
clearContent:{
garbageCollector:true
},
renderDone:{
todoCounter:true //switch to false to see what happens :)
},
destroyContent:{
todoRemover:true
},
createWhenEntered:{
keyboardManager:true
}
};
permissions.validate = function(subscriber, channel){
var test = permissions[channel][subscriber];
return test===undefined? false: test;
};
return permissions;
});
</code></pre>
<p><strong>Subscribers</strong></p>
<p>Found in <code>subscribers.js</code></p>
<p>Subscriber &lsquo;modules&rsquo; communicate through the facade back to the mediator and perform actions when a notification event of a particular name is published.</p>
<p>For example, when a user enters in a new piece of text for a Todo item and hits &lsquo;enter&rsquo; the application publishes a notification saying two things: a) a new Todo item is available and b) the text content of the new item is X. It&rsquo;s then left up to the rest of the application to do with this information whatever it wishes.</p>
<p>In order to update your Backbone application to primarily use pub/sub, a lot of the work you may end up doing will be moving logic coupled inside of specific views to modules outside of it which are reactionary.</p>
<p>Take the <code>todoSaver</code> for example - it&rsquo;s responsibility is saving new Todo items to models once the a <code>notificationName</code> called &lsquo;newContentAvailable&rsquo; has fired. If you take a look at the permissions structure in the last code sample, you&rsquo;ll notice that &lsquo;newContentAvailable&rsquo; is present there. If I wanted to prevent subscribers from being able to subscribe to this notification, I simply set it to a boolean value of <code>false</code>.</p>
<p>Again, this is a massive oversimplification of how advanced your permissions structures could get, but it&rsquo;s certainly one way of controlling what parts of your application can or can&rsquo;t be accessed by specific modules at any time.</p>
<pre><code>define(["jquery", "underscore", "aura/facade"],
function ($, _, facade) {
// Subscription 'modules' for our views. These take the
// the form facade.subscribe( subscriberName, notificationName , callBack )
// Update view with latest todo content
// Subscribes to: newContentAvailable
facade.subscribe('contentUpdater', 'newContentAvailable', function (context) {
var content = context.model.get('content');
context.$('.todo-content').text(content);
context.input = context.$('.todo-input');
context.input.bind('blur', context.close);
context.input.val(content);
});
// Save models when a user has finishes editing
// Subscribes to: endContentEditing
facade.subscribe('todoSaver','endContentEditing', function (context) {
try {
context.model.save({
content: context.input.val()
});
$(context.el).removeClass("editing");
} catch (e) {
//console.log(e);
}
});
// Delete a todo when the user no longer needs it
// Subscribes to: destroyContent
facade.subscribe('todoRemover','destroyContent', function (context) {
try {
context.model.clear();
} catch (e) {
//console.log(e);
}
});
// When a user is adding a new entry, display a tooltip
// Subscribes to: addingNewTodo
facade.subscribe('todoTooltip','addingNewTodo', function (context, todo) {
var tooltip = context.$(".ui-tooltip-top");
var val = context.input.val();
tooltip.fadeOut();
if (context.tooltipTimeout) clearTimeout(context.tooltipTimeout);
if (val == '' || val == context.input.attr('placeholder')) return;
var show = function () {
tooltip.show().fadeIn();
};
context.tooltipTimeout = _.delay(show, 1000);
});
// Update editing UI on switching mode to editing content
// Subscribes to: beginContentEditing
facade.subscribe('editFocus','beginContentEditing', function (context) {
$(context.el).addClass("editing");
context.input.focus();
});
// Create a new todo entry
// Subscribes to: createWhenEntered
facade.subscribe('keyboardManager','createWhenEntered', function (context, e, todos) {
if (e.keyCode != 13) return;
todos.create(context.newAttributes());
context.input.val('');
});
// A Todo and remaining entry counter
// Subscribes to: renderDone
facade.subscribe('todoCounter','renderDone', function (context, Todos) {
var done = Todos.done().length;
context.$('#todo-stats').html(context.statsTemplate({
total: Todos.length,
done: Todos.done().length,
remaining: Todos.remaining().length
}));
});
// Clear all completed todos when clearContent is dispatched
// Subscribes to: clearContent
facade.subscribe('garbageCollector','clearContent', function (Todos) {
_.each(Todos.done(), function (todo) {
todo.clear();
});
});
});
</code></pre>
<p>That&rsquo;s it for this section. If you&rsquo;ve been intrigued by some of the concepts covered, I encourage you to consider taking a look at my <a href="http://addyosmani.com/blog/large-scale-javascript-application-architecture/">slides</a> on Large-scale JS from the jQuery Summit or my longer post on the topic <a href="http://addyosmani.com/largescalejavascript">here</a> for more information.</p>
<h2><a name="pagination">Paginating Backbone.js Requests &amp; Collections</a></h2>
<p>Pagination is a ubiquitous problem we often find ourselves needing to solve on the web. Perhaps most predominantly when working with back-end APIs and JavaScript-heavy clients which consume them.</p>
<p>On this topic, we&rsquo;re going to go through a set of <strong>pagination components </strong> I wrote for Backbone.js, which should hopefully come in useful if you&rsquo;re working on applications which need to tackle this problem. They&rsquo;re part of an extension called <a href="http://github.com/addyosmani/backbone.paginator">Backbone.Paginator</a>.</p>
<p>When working with a structural framework like Backbone.js, the three types of pagination we are most likely to run into are:</p>
<p><strong>Requests to a service layer (API) </strong>- e.g query for results containing the term &lsquo;Brendan&rsquo; - if 5,000 results are available only display 20 results per page (leaving us with 250 possible result pages that can be navigated to).</p>
<p>This problem actually has quite a great deal more to it, such as maintaining persistence of other URL parameters (e.g sort, query, order) which can change based on a user&rsquo;s search configuration in a UI. One also had to think of a clean way of hooking views up to this pagination so you can easily navigate between pages (e.g First, Last, Next, Previous, 1,2,3), manage the number of results displayed per page and so on.</p>
<p><strong>Further client-side pagination of data returned -</strong> e.g we&rsquo;ve been returned a JSON esponse containing 100 results. Rather than displaying all 100 to the user, we only display 20 of these results within a navigatable UI in the browser.</p>
<p>Similar to the request problem, client-pagination has its own challenges like navigation once again (Next, Previous, 1,2,3), sorting, order, switching the number of results to display per page and so on.</p>
<p><strong>Infinite results</strong> - with services such as Facebook, the concept of numeric pagination is instead replaced with a &lsquo;Load More&rsquo; or &lsquo;View More&rsquo; button. Triggering this normally fetches the next &lsquo;page&rsquo; of N results but rather than replacing the previous set of results loaded entirely, we simply append to them instead.</p>
<p>A request pager which simply appends results in a view rather than replacing on each new fetch is effectively an &lsquo;infinite&rsquo; pager.</p>
<p><strong>Let&rsquo;s now take a look at exactly what we&rsquo;re getting out of the box:</strong></p>
<p><em><a href="http://addyosmani.github.com/backbone.paginator/">Backbone.Paginator</a> is a set of opinionated components for paginating collections of data using Backbone.js. It aims to provide both solutions for assisting with pagination of requests to a server (e.g an API) as well as pagination of single-loads of data, where we may wish to further paginate a collection of N results into M pages within a view.</em></p>
<h2>Paginator&rsquo;s pieces</h2>
<p>Backbone.Paginator supports two main pagination components:</p>
<ul>
<li><strong>Backbone.Paginator.requestPager</strong>: For pagination of requests between a client and a server-side API</li>
<li><strong>Backbone.Paginator.clientPager</strong>: For pagination of data returned from a server which you would like to further paginate within the UI (e.g 60 results are returned, paginate into 3 pages of 20)</li>
</ul>
<h2>Downloads And Source Code</h2>
<p>You can either download the raw source code for the project, fork the repository or use one of these links:</p>
<ul>
<li><p>Production: <a href="https://raw.github.com/addyosmani/backbone.baginator/master/dist/backbone.paginator.min.js">production</a></p></li>
<li><p>Development: <a href="https://raw.github.com/addyosmani/backbone.baginator/master/dist/backbone.paginator.js">development version</a></p></li>
<li><p>Examples + Source : <a href="https://github.com/addyosmani/backbone.paginator/zipball/v0.153">zipball</a></p></li>
<li><p><a href="">Repository</a>http://github.com/addyosmani/backbone.paginator)</p></li>
</ul>
<h2>Live Examples</h2>
<p>Live previews of both pagination components using the Netflix API can be found below. Download the tarball or fork the repository to experiment with these examples further.</p>
<p>Demo 1: <a href="http://addyosmani.github.com/backbone.paginator/examples/netflix-request-paging/index.html">Backbone.Paginator.requestPager()</a></p>
<p><img alt="" class="aligncenter size-large wp-image-4578" height="451" src="img/requestPager.png" style="margin-left:-17px;" width="600" /></p>
<p>Demo 2: <a href="http://addyosmani.github.com/backbone.paginator/examples/netflix-client-paging/index.html">Backbone.Paginator.clientPager()</a></p>
<p><img alt="" class="aligncenter size-full wp-image-4579" height="462" src="img/clientPager.png" width="600" /></p>
<p>Demo 3: <a href="http://addyosmani.github.com/backbone.paginator/examples/netflix-infinite-paging/index.html">Infinite Pagination (Backbone.Paginator.requestPager())</a></p>
<p><img alt="" class="aligncenter size-large wp-image-4580" height="451" src="img/infinitepager.png" width="600" /></p>
<h2>Paginator.requestPager</h2>
<p>In this section we&rsquo;re going to walkthrough actually using the requestPager.</p>
<h4>1. Create a new Paginated collection</h4>