Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: gh-pages
9473 lines (8429 sloc) 958.666 kb
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Developing Backbone.js Applications - </title>
<style type="text/css">code{white-space: pre;}</style>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #40a070; }
code > span.fl { color: #40a070; }
code > span.ch { color: #4070a0; }
code > span.st { color: #4070a0; }
code > span.co { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > span.er { color: #ff0000; font-weight: bold; }
</style>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p>
<h1>Developing Backbone.js Applications</h1>
<h3>By Addy Osmani (<a href="http://twitter.com/addyosmani">@addyosmani</a>)</h3>
</p>
<div style="width:500px">
<iframe src="http://ghbtns.com/github-btn.html?user=addyosmani&repo=backbone-fundamentals&type=watch&count=true"
allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.1333103182.html#_=1333404284780&amp;count=horizontal&amp;id=twitter-widget-0&amp;lang=en&amp;original_referer=http%3A%2F%2Faddyosmani.github.com%2Fbackbone-fundamentals%2F&amp;size=m&amp;text=Developing%20Backbone.js%20Applications&amp;url=https%3A%2F%2Fgithub.com%2Faddyosmani%2Fbackbone-fundamentals&amp;via=addyosmani" class="twitter-share-button twitter-count-horizontal" style="width: 107px; height: 20px; " title="Twitter Tweet Button"></iframe>
<script id="twitter-wjs" src="//platform.twitter.com/widgets.js"></script><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>
<p>Available free for open-source reading below or for purchase via the <a href="http://shop.oreilly.com/product/0636920025344.do">O'Reilly store</a>. <a href="https://github.com/addyosmani/backbone-fundamentals/"></br>Pull requests</a> and comments always welcome.</p>
<p><img src="img/oreilly.jpg"/></p>
<a href="http://shop.oreilly.com/product/0636920025344/ReviewSubmit.do?sortby=publicationDate?pageId=0636920025344.IP"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://addyosmani.github.com/backbone-fundamentals/img/helpful.png" alt="Was this helpful? We'd love you to write a review."></a>
<nav id="TOC">
<ul>
<li><a href="#prelude">Prelude</a></li>
<li><a href="#target-audience">Target Audience</a></li>
<li><a href="#acknowledgements">Acknowledgements</a></li>
<li><a href="#credits">Credits</a></li>
<li><a href="#target-version">Target Version</a></li>
<li><a href="#reading">Reading</a></li>
<li><a href="#introduction">Introduction</a><ul>
<li><a href="#what-is-mvc">What Is MVC?</a></li>
<li><a href="#what-is-backbone.js">What is Backbone.js?</a></li>
<li><a href="#when-do-i-need-a-javascript-mvc-framework">When Do I Need A JavaScript MVC Framework?</a></li>
<li><a href="#why-consider-backbone.js">Why Consider Backbone.js?</a></li>
<li><a href="#setting-expectations">Setting Expectations</a></li>
</ul></li>
<li><a href="#fundamentals">Fundamentals</a><ul>
<li><a href="#mvc">MVC</a><ul>
<li><a href="#smalltalk-80-mvc">Smalltalk-80 MVC</a></li>
<li><a href="#mvc-applied-to-the-web">MVC Applied To The Web</a></li>
<li><a href="#client-side-mvc-single-page-apps">Client-Side MVC &amp; Single Page Apps</a></li>
<li><a href="#client-side-mvc---backbone-style">Client-Side MVC - Backbone Style</a></li>
<li><a href="#implementation-specifics">Implementation Specifics</a></li>
</ul></li>
<li><a href="#what-does-mvc-give-us">What does MVC give us?</a><ul>
<li><a href="#delving-deeper-into-mvc">Delving Deeper into MVC</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#further-reading">Further reading</a></li>
</ul></li>
<li><a href="#fast-facts">Fast facts</a><ul>
<li><a href="#backbone.js">Backbone.js</a></li>
<li><a href="#used-by">Used by</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-basics">Backbone Basics</a><ul>
<li><a href="#getting-set-up">Getting set up</a></li>
<li><a href="#models-1">Models</a></li>
<li><a href="#views-1">Views</a></li>
<li><a href="#collections">Collections</a></li>
<li><a href="#restful-persistence">RESTful Persistence</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#routers">Routers</a></li>
<li><a href="#backbones-sync-api">Backbone’s Sync API</a></li>
<li><a href="#dependencies">Dependencies</a></li>
<li><a href="#summary-1">Summary</a></li>
</ul></li>
<li><a href="#exercise-1-todos---your-first-backbone.js-app">Exercise 1: Todos - Your First Backbone.js App</a><ul>
<li><a href="#static-html">Static HTML</a></li>
<li><a href="#todo-model">Todo model</a></li>
<li><a href="#todo-collection">Todo collection</a></li>
<li><a href="#application-view">Application View</a></li>
<li><a href="#individual-todo-view">Individual Todo View</a></li>
<li><a href="#startup">Startup</a></li>
<li><a href="#in-action">In action</a></li>
<li><a href="#completing-deleting-todos">Completing &amp; deleting todos</a></li>
<li><a href="#todo-routing">Todo routing</a></li>
<li><a href="#summary-2">Summary</a></li>
</ul></li>
<li><a href="#exercise-2-book-library---your-first-restful-backbone.js-app">Exercise 2: Book Library - Your First RESTful Backbone.js App</a><ul>
<li><a href="#setting-up">Setting up</a></li>
<li><a href="#wiring-in-the-interface">Wiring in the interface</a><ul>
<li><a href="#adding-models">Adding models</a></li>
<li><a href="#removing-models">Removing models</a></li>
</ul></li>
<li><a href="#creating-the-back-end">Creating the back-end</a><ul>
<li><a href="#install-node.js-npm-and-mongodb">Install node.js, npm, and MongoDB</a></li>
<li><a href="#install-node-modules">Install node modules</a></li>
<li><a href="#create-a-simple-web-server">Create a simple web server</a></li>
<li><a href="#connect-to-the-database">Connect to the database</a></li>
</ul></li>
<li><a href="#talking-to-the-server">Talking to the server</a><ul>
<li><a href="#summary-3">Summary</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-extensions">Backbone Extensions</a><ul>
<li><a href="#marionettejs-backbone.marionette">MarionetteJS (Backbone.Marionette)</a><ul>
<li><a href="#boilerplate-rendering-code">Boilerplate Rendering Code</a></li>
<li><a href="#reducing-boilerplate-with-marionette.itemview">Reducing Boilerplate With Marionette.ItemView</a></li>
<li><a href="#memory-management">Memory Management</a></li>
<li><a href="#region-management">Region Management</a></li>
<li><a href="#marionette-todo-app">Marionette Todo app</a></li>
<li><a href="#is-the-marionette-implementation-of-the-todo-app-more-maintainable">Is the Marionette implementation of the Todo app more maintainable?</a></li>
<li><a href="#marionette-and-flexibility">Marionette And Flexibility</a></li>
<li><a href="#and-so-much-more">And So Much More</a></li>
</ul></li>
<li><a href="#thorax">Thorax</a><ul>
<li><a href="#hello-world">Hello World</a></li>
<li><a href="#embedding-child-views">Embedding child views</a></li>
<li><a href="#view-helpers">View helpers</a></li>
<li><a href="#collection-helper">collection helper</a></li>
<li><a href="#custom-html-data-attributes">Custom HTML data attributes</a></li>
<li><a href="#thorax-resources">Thorax Resources</a></li>
</ul></li>
</ul></li>
<li><a href="#common-problems-solutions">Common Problems &amp; Solutions</a></li>
<li><a href="#modular-development">Modular Development</a><ul>
<li><a href="#introduction-1">Introduction</a></li>
<li><a href="#organizing-modules-with-requirejs-and-amd">Organizing modules with RequireJS and AMD</a><ul>
<li><a href="#maintainability-problems-with-multiple-script-files">Maintainability problems with multiple script files</a></li>
<li><a href="#need-for-better-dependency-management">Need for better dependency management</a></li>
<li><a href="#asynchronous-module-definition-amd">Asynchronous Module Definition (AMD)</a></li>
<li><a href="#writing-amd-modules-with-requirejs">Writing AMD modules with RequireJS</a></li>
<li><a href="#getting-started-with-requirejs">Getting Started with RequireJS</a></li>
<li><a href="#require.js-and-backbone-examples">Require.js and Backbone Examples</a></li>
<li><a href="#keeping-your-templates-external-using-requirejs-and-the-text-plugin">Keeping Your Templates External Using RequireJS And The Text Plugin</a></li>
<li><a href="#optimizing-backbone-apps-for-production-with-the-requirejs-optimizer">Optimizing Backbone apps for production with the RequireJS Optimizer</a></li>
</ul></li>
</ul></li>
<li><a href="#exercise-3-your-first-modular-backbone-requirejs-app">Exercise 3: Your First Modular Backbone + RequireJS App</a><ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#markup">Markup</a></li>
<li><a href="#configuration-options">Configuration options</a></li>
<li><a href="#modularizing-our-models-views-and-collections">Modularizing our models, views and collections</a></li>
<li><a href="#route-based-module-loading">Route-based module loading</a><ul>
<li><a href="#json-based-module-configuration">JSON-based module configuration</a></li>
<li><a href="#module-loader-router">Module loader Router</a></li>
<li><a href="#using-nodejs-to-handle-pushstate">Using NodeJS to handle pushState</a></li>
</ul></li>
<li><a href="#an-asset-package-alternative-for-dependency-management">An asset package alternative for dependency management</a></li>
</ul></li>
<li><a href="#paginating-backbone.js-requests-collections">Paginating Backbone.js Requests &amp; Collections</a><ul>
<li><a href="#introduction-2">Introduction</a><ul>
<li><a href="#backbone.paginator">Backbone.Paginator</a></li>
<li><a href="#live-examples">Live Examples</a></li>
</ul></li>
<li><a href="#paginator.requestpager">Paginator.requestPager</a></li>
<li><a href="#gotchas">Gotchas!</a></li>
<li><a href="#gotchas-1">Gotchas!</a></li>
<li><a href="#paginator.clientpager">Paginator.clientPager</a><ul>
<li><a href="#plugins">Plugins</a></li>
<li><a href="#bootstrapping">Bootstrapping</a></li>
<li><a href="#styling">Styling</a></li>
<li><a href="#conclusions">Conclusions</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-boilerplate-and-grunt-bbb">Backbone Boilerplate And Grunt-BBB</a><ul>
<li><a href="#getting-started">Getting Started</a><ul>
<li><a href="#backbone-boilerplate-and-grunt-bbb-1">Backbone Boilerplate and Grunt-BBB</a></li>
</ul></li>
<li><a href="#creating-a-new-project">Creating a new project</a><ul>
<li><a href="#index.html">index.html</a></li>
<li><a href="#config.js">config.js</a></li>
<li><a href="#main.js">main.js</a></li>
<li><a href="#app.js">app.js</a></li>
<li><a href="#creating-backbone-boilerplate-modules">Creating Backbone Boilerplate Modules</a></li>
<li><a href="#router.js">router.js</a></li>
</ul></li>
<li><a href="#other-useful-tools-projects">Other Useful Tools &amp; Projects</a><ul>
<li><a href="#yeoman">Yeoman</a></li>
<li><a href="#backbone-devtools">Backbone DevTools</a></li>
</ul></li>
<li><a href="#conclusions-1">Conclusions</a></li>
</ul></li>
<li><a href="#backbone-jquery-mobile">Backbone &amp; jQuery Mobile</a><ul>
<li><a href="#mobile-app-development-with-jquery-mobile">Mobile app development with jQuery Mobile</a></li>
<li><a href="#basic-backbone-app-setup-for-jquery-mobile">Basic Backbone app setup for jQuery Mobile</a></li>
<li><a href="#workflow-with-backbone-and-jquerymobile">Workflow with Backbone and jQueryMobile</a></li>
<li><a href="#applying-advanced-jqm-techniques-to-backbone">Applying advanced jQM techniques to Backbone</a></li>
</ul></li>
<li><a href="#unit-testing">Unit Testing</a></li>
<li><a href="#jasmine">Jasmine</a><ul>
<li><a href="#behavior-driven-development">Behavior-Driven Development</a></li>
<li><a href="#suites-specs-spies">Suites, Specs, &amp; Spies</a></li>
<li><a href="#beforeeach-and-aftereach">beforeEach() and afterEach()</a></li>
<li><a href="#shared-scope">Shared scope</a></li>
<li><a href="#getting-set-up-1">Getting set up</a></li>
<li><a href="#tdd-with-backbone">TDD With Backbone</a></li>
<li><a href="#models-2">Models</a></li>
<li><a href="#collections-1">Collections</a></li>
<li><a href="#views-2">Views</a><ul>
<li><a href="#view-testing">View testing</a></li>
</ul></li>
<li><a href="#conclusions-2">Conclusions</a></li>
<li><a href="#exercise">Exercise</a></li>
<li><a href="#further-reading-1">Further reading</a></li>
</ul></li>
<li><a href="#qunit">QUnit</a><ul>
<li><a href="#introduction-3">Introduction</a></li>
<li><a href="#getting-setup">Getting Setup</a></li>
<li><a href="#assertions">Assertions</a></li>
<li><a href="#adding-structure-to-assertions">Adding structure to assertions</a></li>
<li><a href="#assertion-examples">Assertion examples</a><ul>
<li><a href="#equal---a-comparison-assertion.-it-passes-if-actual-expected">equal - a comparison assertion. It passes if actual == expected</a></li>
<li><a href="#notequal---a-comparison-assertion.-it-passes-if-actual-expected">notEqual - a comparison assertion. It passes if actual != expected</a></li>
<li><a href="#strictequal---a-comparison-assertion.-it-passes-if-actual-expected">strictEqual - a comparison assertion. It passes if actual === expected</a></li>
<li><a href="#notstrictequal---a-comparison-assertion.-it-passes-if-actual-expected">notStrictEqual - a comparison assertion. It passes if actual !== expected</a></li>
<li><a href="#deepequal---a-recursive-comparison-assertion.-unlike-strictequal-it-works-on-objects-arrays-and-primitives.">deepEqual - a recursive comparison assertion. Unlike strictEqual(), it works on objects, arrays and primitives.</a></li>
<li><a href="#notdeepequal---a-comparison-assertion.-this-returns-the-opposite-of-deepequal">notDeepEqual - a comparison assertion. This returns the opposite of deepEqual</a></li>
<li><a href="#raises---an-assertion-which-tests-if-a-callback-throws-any-exceptions">raises - an assertion which tests if a callback throws any exceptions</a></li>
</ul></li>
<li><a href="#fixtures">Fixtures</a><ul>
<li><a href="#fixtures-example">Fixtures example:</a></li>
</ul></li>
<li><a href="#asynchronous-code">Asynchronous code</a></li>
</ul></li>
<li><a href="#sinonjs">SinonJS</a><ul>
<li><a href="#what-is-sinonjs">What is SinonJS?</a></li>
<li><a href="#stubs-and-mocks">Stubs and mocks</a><ul>
<li><a href="#stubs">Stubs</a></li>
<li><a href="#mocks">Mocks</a></li>
</ul></li>
<li><a href="#exercise-1">Exercise</a><ul>
<li><a href="#models-3">Models</a></li>
<li><a href="#collections-2">Collections</a></li>
<li><a href="#views-3">Views</a></li>
<li><a href="#app">App</a></li>
</ul></li>
<li><a href="#further-reading-resources">Further Reading &amp; Resources</a></li>
</ul></li>
<li><a href="#resources">Resources</a><ul>
<li><a href="#books-courses">Books &amp; Courses</a></li>
<li><a href="#extensionslibraries">Extensions/Libraries</a></li>
</ul></li>
<li><a href="#conclusions-3">Conclusions</a></li>
<li><a href="#appendix">Appendix</a><ul>
<li><a href="#a-simple-javascript-mvc-implementation">A Simple JavaScript MVC Implementation</a><ul>
<li><a href="#event-system">Event System</a></li>
<li><a href="#models-4">Models</a></li>
<li><a href="#views-4">Views</a></li>
<li><a href="#controllers-2">Controllers</a></li>
<li><a href="#practical-usage">Practical Usage</a></li>
</ul></li>
<li><a href="#mvp">MVP</a><ul>
<li><a href="#models-views-presenters">Models, Views &amp; Presenters</a></li>
</ul></li>
<li><a href="#mvp-or-mvc">MVP or MVC?</a></li>
<li><a href="#mvc-mvp-and-backbone.js">MVC, MVP and Backbone.js</a></li>
<li><a href="#namespacing">Namespacing</a></li>
<li><a href="#backbone-dependency-details">Backbone Dependency Details</a><ul>
<li><a href="#dom-manipulation">DOM Manipulation</a></li>
<li><a href="#utilities">Utilities</a></li>
<li><a href="#restful-persistence-1">RESTful persistence</a></li>
<li><a href="#routing">Routing</a></li>
</ul></li>
<li><a href="#backbone-vs.-other-libraries-and-frameworks">Backbone Vs. Other Libraries And Frameworks</a></li>
</ul></li>
</ul>
</nav>
<h2 id="prelude">Prelude</h2>
<figure>
<img src="img/logo.jpg" />
</figure>
<p>Not so long ago, “data-rich web application” was an oxymoron. Today, these applications are everywhere and you need to know how to build them.</p>
<p>Traditionally, web applications left the heavy-lifting of data to servers that pushed HTML to the browser in complete page loads. The use of client-side JavaScript was limited to improving the user experience. Now this relationship has been inverted - client applications pull raw data from the server and render it into the browser when and where it is needed.</p>
<p>Think of the Ajax shopping cart which doesn’t require a refresh on the page when adding an item to your basket. Initially, jQuery became the go-to library for this paradigm. Its nature was to make Ajax requests then update text on the page and so on. However, this pattern with jQuery revealed that we have implicit model data on the client side. With the server no longer being the only place that knows about our item count, it was a hint that there was a natural tension and pull of this evolution.</p>
<p>The rise of arbitrary code on the client-side which can talk to the server however it sees fit has meant an increase in client-side complexity. Good architecture on the client has gone from an afterthought to essential - you can’t just hack together some jQuery code and expect it to scale as your application grows. Most likely, you would end up with a nightmarish tangle of UI callbacks entwined with business logic, destined to be discarded by the poor soul who inherits your code.</p>
<p>Thankfully, there are a growing number of JavaScript libraries that can help improve the structure and maintainability of your code, making it easier to build ambitious interfaces without a great deal of effort. <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> has quickly become one of the most popular open-source solutions to these issues and in this book we will take you through an in-depth walkthrough of it.</p>
<p>Begin with the fundamentals, work your way through the exercises, and learn how to build an application that is both cleanly organized and maintainable. If you are a developer looking to write code that can be more easily read, structured, and extended - this guide can help.</p>
<p>Improving developer education is important to me, which is why this book 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>. This means you can purchase or grab a copy of the book for <a href="http://addyosmani.github.com/backbone-fundamentals/">free</a> or help to further <a href="https://github.com/addyosmani/backbone-fundamentals/">improve</a> it. 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.</p>
<p>My extended thanks go out to <a href="https://github.com/jashkenas">Jeremy Ashkenas</a> and <a href="http://www.documentcloud.org">DocumentCloud</a> for creating Backbone.js and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">these</a> members of the community for their assistance making this project far better than I could have imagined.</p>
<h2 id="target-audience">Target Audience</h2>
<p>This book is targeted at novice to intermediate developers wishing to learn how to better structure their client-side code. An understanding of JavaScript fundamentals is required to get the most out of it, however we have tried to provide a basic description of these concepts where possible.</p>
<h2 id="acknowledgements">Acknowledgements</h2>
<p>I am indebted to the fantastic work done by the technical reviewers who helped review and improve this book. Their knowledge, energy, and passion have helped shape it into a better learning resource and they continue to serve as a source of inspiration. Thanks go out to:</p>
<ul>
<li><a href="https://github.com/dcmaf">Marc Friedman</a></li>
<li><a href="https://github.com/derickbailey">Derick Bailey</a></li>
<li><a href="https://github.com/jashkenas">Jeremy Ashkenas</a></li>
<li><a href="https://github.com/samuelclay">Samuel Clay</a></li>
<li><a href="http://github.com/wibblymat">Mat Scales</a></li>
<li><a href="https://github.com/alexgraul">Alex Graul</a></li>
<li><a href="https://github.com/g6scheme">Dusan Gledovic</a></li>
<li><a href="https://github.com/sindresorhus">Sindre Sorhus</a></li>
</ul>
<p>I would also like to thank my loving family for their patience and support while I worked on this book, as well as my brilliant editor Mary Treseler.</p>
<h2 id="credits">Credits</h2>
<p>None of this work would have been possible without the time and effort invested by the other developers and authors in the community who helped contribute to it. I would like to extend my thanks to:</p>
<ul>
<li>Derick and Marc (once again)</li>
<li><a href="https://github.com/eastridge">Ryan Eastridge</a></li>
<li><a href="https://github.com/jackfranklin">Jack Franklin</a></li>
<li><a href="https://github.com/raDiesle">David Amend</a></li>
<li><a href="https://github.com/mdb">Mike Ball</a></li>
<li>Will Sulzer</li>
<li><a href="https://github.com/ugisozols">Uģis Ozols</a></li>
<li><a href="https://github.com/Ekengren">Björn Ekengren</a></li>
</ul>
<p>as well as our other excellent <a href="https://github.com/addyosmani/backbone-fundamentals/graphs/contributors">contributors</a> that made this project possible.</p>
<h2 id="target-version">Target Version</h2>
<p>Developing Backbone.js Applications targets Backbone.js 1.1.x (and Underscore 1.6.x) and will actively attempt to stay up to date with more recent versions of these libraries. Where possible, if you find using a newer version of Backbone breaks an example, please consult the official guide to <a href="http://backbonejs.org/#upgrading">upgrading</a> as it contains instructions for how to work around breaking changes. StackOverflow also contains many excellent examples of how other users are handling updating their code.</p>
<h2 id="reading">Reading</h2>
<p>I assume your level of knowledge about JavaScript goes beyond the basics and as such certain topics such as object literals are skipped. If you need to learn more about the language, I am happy to suggest:</p>
<ul>
<li><a href="http://eloquentjavascript.net/">Eloquent JavaScript</a></li>
<li><a href="http://shop.oreilly.com/product/9780596805531.do">JavaScript: The Definitive Guide</a> by David Flanagan (O’Reilly)</li>
<li><a href="http://www.informit.com/store/effective-javascript-68-specific-ways-to-harness-the-9780321812186">Effective JavaScript</a> by David Herman (Pearson)</li>
<li><a href="http://shop.oreilly.com/product/9780596517748.do">JavaScript: The Good Parts</a> by Douglas Crockford (O’Reilly)</li>
<li><a href="http://www.amazon.com/Object-Oriented-Javascript-Stoyan-Stefanov/dp/1847194141">Object-Oriented JavaScript</a> by Stoyan Stefanov (Packt Publishing)</li>
</ul>
<h1 id="introduction">Introduction</h1>
<p>Frank Lloyd Wright once said “You can’t make an architect. You can however open the doors and windows toward the light as you see it.” In this book, I hope to shed some light on how to improve the structure of your web applications, opening doors to what will hopefully be more maintainable, readable applications in your future.</p>
<p>The goal of all architecture is to build something well; in our case, to craft code that is enduring and delights both ourselves and the developers who will maintain our code long after we are gone. We all want our architecture to be simple, yet beautiful.</p>
<p>Modern JavaScript frameworks and libraries can bring structure and organization to your projects, establishing a maintainable foundation right from the start. They build on the trials and tribulations of developers who have had to work around callback chaos similar to that which you are facing now or may in the near future.</p>
<p>When developing applications using just jQuery, the piece missing is a way to structure and organize your code. It’s very easy to create a JavaScript app that ends up a tangled mess of jQuery selectors and callbacks, all desperately trying to keep data in sync between the HTML for your UI, the logic in your JavaScript, and calls to your API for data.</p>
<p>Without something to help tame the mess, you’re likely to string together a set of independent plugins and libraries to make up the functionality or build everything yourself from scratch and have to maintain it yourself. Backbone solves this problem for you, providing a way to cleanly organize code, separating responsibilities into recognizable pieces that are easy to maintain.</p>
<p>In “Developing Backbone.js Applications,” I and a number of other experienced authors will show you how to improve your web application structure using the popular JavaScript library, Backbone.js</p>
<h3 id="what-is-mvc">What Is MVC?</h3>
<p>A number of modern JavaScript frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application into three parts:</p>
<ul>
<li>Models represent the domain-specific knowledge and data in an application. Think of this as being a ‘type’ of data you can model — like a User, Photo, or Todo note. Models can notify observers when their state changes.</li>
<li>Views typically constitute the user interface in an application (e.g., markup and templates), but don’t have to be. They observe Models, but don’t directly communicate with them.</li>
<li>Controllers handle input (e.g., clicks, user actions) and update Models.</li>
</ul>
<p>Thus, in an MVC application, user input is acted upon by Controllers which update Models. Views observe Models and update the user interface when changes occur.</p>
<p>JavaScript MVC frameworks don’t always strictly follow the above pattern. Some solutions (including Backbone.js) merge the responsibility of the Controller into the View, while other approaches add additional components into the mix.</p>
<p>For this reason we refer to such frameworks as following the MV* pattern; that is, you’re likely to have a Model and a View, but a distinct Controller might not be present and other components may come into play.</p>
<h3 id="what-is-backbone.js">What is Backbone.js?</h3>
<figure>
<img src="img/backbonejsorg.jpg" />
</figure>
<p>Backbone.js is a lightweight JavaScript library that adds structure to your client-side code. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.</p>
<p>Developers commonly use libraries like Backbone.js to create single-page applications (SPAs). SPAs are web applications that load into the browser and then react to data changes on the client side without requiring complete page refreshes from the server.</p>
<p>Backbone is mature, popular, and has both a vibrant developer community as well as a wealth of plugins and extensions available that build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and LinkedIn.</p>
<p>Backbone focuses on giving you helpful methods for querying and manipulating your data rather than re-inventing the JavaScript object model. It’s a library, rather than a framework, that plays well with others and scales well, from embedded widgets to large-scale applications.</p>
<p>As it’s small, there is also less your users have to download on mobile or slower connections. The entire Backbone source can be read and understood in just a few hours.</p>
<h3 id="when-do-i-need-a-javascript-mvc-framework">When Do I Need A JavaScript MVC Framework?</h3>
<p>When building a single-page application using JavaScript, whether it involves a complex user interface or is simply trying to reduce the number of HTTP requests required for new Views, you will likely find yourself inventing many of the pieces that make up an MV* framework.</p>
<p>At the outset, it isn’t terribly difficult to write your own application framework that offers some opinionated way to avoid spaghetti code; however, to say that it is equally as trivial to write something as robust as Backbone would be a grossly incorrect assumption.</p>
<p>There’s a lot more that goes into structuring an application than tying together a DOM manipulation library, templating, and routing. Mature MV* frameworks typically include not only the pieces you would find yourself writing, but also include solutions to problems you’ll find yourself running into later on down the road. This is a time-saver that you shouldn’t underestimate the value of.</p>
<p>So, where will you likely need an MV* framework and where won’t you?</p>
<p>If you’re writing an application where much of the heavy lifting for view rendering and data manipulation will be occurring in the browser, you may find a JavaScript MV* framework useful. Examples of applications that fall into this category are GMail, NewsBlur and the LinkedIn mobile app.</p>
<p>These types of applications typically download a single payload containing all the scripts, stylesheets, and markup users need for common tasks and then perform a lot of additional behavior in the background. For instance, it’s trivial to switch between reading an email or document to writing one without sending a new page request to the server.</p>
<p>If, however, you’re building an application that still relies on the server for most of the heavy-lifting of page/view rendering and you’re just using a little JavaScript or jQuery to make things more interactive, an MV* framework may be overkill. There certainly are complex Web applications where the partial rendering of views can be coupled with a single-page application effectively, but for everything else, you may find yourself better sticking to a simpler setup.</p>
<p>Maturity in software (framework) development isn’t simply about how long a framework has been around. It’s about how solid the framework is and more importantly how well it’s evolved to fill its role. Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it?</p>
<h3 id="why-consider-backbone.js">Why Consider Backbone.js?</h3>
<p>Backbone provides a minimal set of data-structuring (Models, Collections) and user interface (Views, URLs) primitives that are helpful when building dynamic applications using JavaScript. It’s not opinionated, meaning you have the freedom and flexibility to build the best experience for your web application how you see fit. You can either use the prescribed architecture it offers out of the box or extend it to meet your requirements.</p>
<p>The library doesn’t focus on widgets or replacing the way you structure objects - it just supplies you with utilities for manipulating and querying data in your application. Backbone also doesn’t prescribe a specific template engine. While you are free to use the micro-templating offered by Underscore.js (Backbone’s only hard dependency), views can bind to HTML constructed using your templating solution of choice.</p>
<p>Looking at the <a href="http://backbonejs.org/#examples">large</a> number of applications built with Backbone, it’s clear that it scales well. Backbone also works quite well with other libraries, meaning you can embed Backbone widgets in an application written with AngularJS, use it with TypeScript, or just use an individual class (like Models) as a data backer for simpler apps.</p>
<p>There are no performance drawbacks to using Backbone to structure your application. It avoids run loops, two-way binding, and constant polling of your data structures for updates and tries to keep things simple where possible. That said, should you wish to go against the grain, you can of course implement such things on top of it. Backbone won’t stop you.</p>
<p>With a vibrant community of plugin and extension authors, there’s a likelihood that if you’re looking to achieve some behavior Backbone is lacking, a complementary project exists that works well with it. This is made simpler by Backbone offering literate documentation of its source code, allowing anyone an opportunity to easily understand what is going on behind the scenes.</p>
<p>Having been refined over two and a half years of development, Backbone is a mature library that will continue to offer a minimalist solution for building better web applications. I regularly use it and hope that you find it as useful an addition to your toolbelt as I have.</p>
<h3 id="setting-expectations">Setting Expectations</h3>
<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 an issue (or better yet, a pull-request) on the book’s <a href="https://github.com/addyosmani/backbone-fundamentals">GitHub site</a>. It won’t take long and you’ll be helping other developers avoid the problems you ran into.</p>
<p>Topics will include MVC theory and how to build applications using Backbone’s Models, Views, Collections, and Routers. I’ll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), solutions to common problems like nested views, how to solve routing problems with Backbone and jQuery Mobile, and much more.</p>
<p>Here is a peek at what you will be learning in each chapter:</p>
<p><i>Chapter 2, Fundamentals</i>, traces the history of the MVC design pattern and introduces how it is implemented by Backbone.js and other JavaScript frameworks.</p>
<p><i>Chapter 3, Backbone Basics</i>, covers the major features of the Backbone.js core and the technologies and techniques you will need to know in order to apply it.</p>
<p><i>Chapter 4, Exercise 1: Todos - Your First Backbone.js App</i>, takes you step-by-step through development of a simple client-side Todo List application.</p>
<p><i>Chapter 5, Exercise 2: Book Library - Your First RESTful Backbone.js App</i>, walks you through development of a Book Library application which persists its model to a server using a REST API.</p>
<p><i>Chapter 6, Backbone Extensions</i>, describes Backbone.Marionette and Thorax, two extension frameworks which add features to Backbone.js that are useful for developing large-scale applications.</p>
<p><i>Chapter 7, Common Problems and Solutions</i>, reviews common issues you may encounter when using Backbone.js and ways of addressing them.</p>
<p><i>Chapter 8, Modular Development</i>, looks at how AMD modules and RequireJS can be used to modularize your code.</p>
<p><i>Chapter 9, Exercise 3: Todos - Your First Modular Backbone + RequireJS App</i>, takes you through rewriting the app created in Exercise 1 to be more modular with the help of RequireJS.</p>
<p><i>Chapter 10, Paginating Backbone Requests &amp; Collections</i>, walks through how to use the Backbone.Paginator plugin to paginate data for your Collections.</p>
<p><i>Chapter 11, Backbone Boilerplate And Grunt BBB</i>, introduces powerful tools you can use to bootstrap a new Backbone.js application with boilerplate code.</p>
<p><i>Chapter 12, Mobile Applications</i>, addresses the issues that arise when using Backbone with jQuery Mobile.</p>
<p><i>Chapter 13, Jasmine</i>, covers how to unit test Backbone code using the Jasmine test framework.</p>
<p><i>Chapter 14, QUnit</i>, discusses how to use QUnit for unit testing.</p>
<p><i>Chapter 15, SinonJS</i>, discusses how to use SinonJS for unit testing your Backbone apps.</p>
<p><i>Chapter 16, Resources</i>, provides references to additional Backbone-related resources.</p>
<p><i>Chapter 17, Conclusions</i>, wraps up our tour through the world of Backbone.js development.</p>
<p><i>Chapter 18, Appendix</i>, returns to our design pattern discussion by contrasting MVC with the Model-View-Presenter (MVP) pattern and examines how Backbone.js relates to both. A walkthrough of writing a Backbone-like library from scratch and other topics are also covered.</p>
<h1 id="fundamentals">Fundamentals</h1>
<p>Design patterns are proven solutions to common development problems that can help us improve the organization and structure of our applications. By using patterns, we benefit from the collective experience of skilled developers who have repeatedly solved similar problems.</p>
<p>Historically, developers creating desktop and server-class applications have had a wealth of design patterns available for them to lean on, but it’s only been in the past few years that such patterns have been applied to client-side development.</p>
<p>In this chapter, we’re going to explore the evolution of the Model-View-Controller (MVC) design pattern and get our first look at how Backbone.js allows us to apply this pattern to client-side development.</p>
<h2 id="mvc">MVC</h2>
<p>MVC 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 managing logic, user-input, and 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 “GoF” or “Gang of Four” book) in 1994, which played a role in popularizing its use.</p>
<h3 id="smalltalk-80-mvc">Smalltalk-80 MVC</h3>
<p>It’s important to understand the issues that the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70’s, graphical user-interfaces were few and far 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’s screen.</p>
<p>The Smalltalk-80 implementation of MVC took this concept further and had an objective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of Models for other interfaces in the application. There are some interesting points worth noting about Smalltalk-80’s MVC architecture:</p>
<ul>
<li>A Domain element was known as a Model and was ignorant of the user-interface (Views and Controllers)</li>
<li>Presentation was taken care of by the View and the Controller, but there wasn’t just a single View and Controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them</li>
<li>The Controller’s role in this pair was handling user input (such as key-presses and click events) and doing something sensible with them</li>
<li>The Observer pattern was used to update 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’s architecture decades ago. In Smalltalk-80’s MVC, the View and Controller both observe the Model: anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - for the application to show real-time information, any change to the data in its Model 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’s MVC, I recommend reading his work.</p>
<h3 id="mvc-applied-to-the-web">MVC Applied To The Web</h3>
<p>The web heavily relies on the HTTP protocol, which is stateless. This means that there is not a constantly open connection between the browser and server; each request instantiates a new communication channel between the two. Once the request initiator (e.g. a browser) gets a response the connection is closed. This fact creates a completely different context when compared to one of the operating systems on which many of the original MVC ideas were developed. The MVC implementation has to conform to the web context.</p>
<p>An example of a server-side web application framework which tries to apply MVC to the web context is <a href="http://guides.rubyonrails.org/">Ruby On Rails</a>.</p>
<figure>
<img src="img/rails_mvc.png" />
</figure>
<p>At its core are the three MVC components we would expect - the Model, View and Controller architecture. In Rails:</p>
<ul>
<li>Models represent the data in an application and are typically used to manage rules for interacting with a specific database table. You generally have one table corresponding to one model with much of your application’s business logic living within these models.</li>
<li>Views represent your user interface, often taking the form of HTML that will be sent down to the browser. They’re used to present application data to anything making requests from your application.</li>
<li>Controllers offer the glue between models and views. Their responsibility is to process requests from the browser, ask your models for data and then supply this data to views so that they may be presented to the browser.</li>
</ul>
<p>Although there’s a clear separation of concerns that is MVC-like in Rails, it is actually using a different pattern called <a href="http://en.wikipedia.org/wiki/Model2">Model2</a>. One reason for this is that Rails does not notify views from the model or controllers - it just passes model data directly to the view.</p>
<p>That said, even for the server-side workflow of receiving a request from a URL, baking out an HTML page as a response and separating your business logic from your interface has many benefits. In the same way that keeping your UI cleanly separate from your database records is useful in server-side frameworks, it’s equally as useful to keep your UI cleanly separated from your data models in JavaScript (as we will read more about shortly).</p>
<p>Other server-side implementations of MVC (such as the PHP <a href="http://zend.com">Zend</a> framework) also implement the <a href="http://en.wikipedia.org/wiki/Front_Controller_pattern">Front Controller</a> design pattern. This pattern layers an MVC stack behind a single point of entry. This single point of entry means that all HTTP requests (e.g., <code>http://www.example.com</code>, <code>http://www.example.com/whichever-page/</code>, etc.) are routed by the server’s configuration to the same handler, independent of the URI.</p>
<p>When the Front Controller receives an HTTP request it analyzes it and decides which class (Controller) and method (Action) to invoke. The selected Controller Action takes over and interacts with the appropriate Model to fulfill the request. The Controller receives data back from the Model, loads an appropriate View, injects the Model data into it, and returns the response to the browser.</p>
<p>For example, let’s say we have our blog on <code>www.example.com</code> and we want to edit an article (with <code>id=43</code>) and request <code>http://www.example.com/article/edit/43</code>:</p>
<p>On the server side, the Front Controller would analyze the URL and invoke the Article Controller (corresponding to the <code>/article/</code> part of the URI) and its Edit Action (corresponding to the <code>/edit/</code> part of the URI). Within the Action there would be a call to, let’s say, the Articles Model and its <code>Articles::getEntry(43)</code> method (43 corresponding to the <code>/43</code> at the end of the URI). This would return the blog article data from the database for editing. The Article Controller would then load the (<code>article/edit</code>) View which would include logic for injecting the article’s data into a form suitable for editing its content, title, and other (meta) data. Finally, the resulting HTML response would be returned to the browser.</p>
<p>As you can imagine, a similar flow is necessary with POST requests after we press a save button in a form. The POST action URI would look like <code>/article/save/43</code>. The request would go through the same Controller, but this time the Save Action would be invoked (due to the <code>/save/</code> URI chunk), the Articles Model would save the edited article to the database with <code>Articles::saveEntry(43)</code>, and the browser would be redirected to the <code>/article/edit/43</code> URI for further editing.</p>
<p>Finally, if the user requested <code>http://www.example.com/</code> the Front Controller would invoke the default Controller and Action; e.g., the Index Controller and its Index action. Within Index Action there would be a call to the Articles model and its <code>Articles::getLastEntries(10)</code> method which would return the last 10 blog posts. The Controller would load the blog/index View which would have basic logic for listing the blog posts.</p>
<p>The picture below shows this typical HTTP request/response lifecycle for server-side MVC:</p>
<figure>
<img src="img/webmvcflow_bacic.png" />
</figure>
<p>The Server receives an HTTP request and routes it through a single entry point. At that entry point, the Front Controller analyzes the request and based on it invokes an Action of the appropriate Controller. This process is called routing. The Action Model is asked to return and/or save submitted data. The Model communicates with the data source (e.g., database or API). Once the Model completes its work it returns data to the Controller which then loads the appropriate View. The View executes presentation logic (loops through articles and prints titles, content, etc.) using the supplied data. In the end, an HTTP response is returned to the browser.</p>
<h3 id="client-side-mvc-single-page-apps">Client-Side MVC &amp; Single Page Apps</h3>
<p>Several <a href="http://radar.oreilly.com/2009/07/velocity-making-your-site-fast.html">studies</a> have confirmed that improvements to latency can have a positive impact on the usage and user engagement of sites and apps. This is at odds with the traditional approach to web app development which is very server-centric, requiring a complete page reload to move from one page to the next. Even with heavy caching in place, the browser still has to parse the CSS, JavaScript, and HTML and render the interface to the screen.</p>
<p>In addition to resulting in a great deal of duplicated content being served back to the user, this approach affects both latency and the general responsiveness of the user experience. A trend to improve perceived latency in the past few years has been to move towards building Single Page Applications (SPAs) - apps which after an initial page load are able to handle subsequent navigations and requests for data without the need for a complete reload.</p>
<p>When a user navigates to a new view, additional content required for the view is requested using an XHR (XMLHttpRequest), typically communicating with a server-side REST API or endpoint. <a href="https://en.wikipedia.org/wiki/Ajax_(programming)">Ajax</a> (Asynchronous JavaScript and XML) makes communication with the server asynchronous so that data is transferred and processed in the background, allowing the user to interact with other parts of a page without interruption. This improves usability and responsiveness.</p>
<p>SPAs can also take advantage of browser features like the <a href="http://diveintohtml5.info/history.html">History API</a> to update the address seen in the location bar when moving from one view to another. These URLs also make it possible to bookmark and share a particular application state, without the need to navigate to completely new pages.</p>
<p>The typical SPA consists of smaller pieces of interface representing logical entities, all of which have their own UI, business logic and data. A good example is a basket in a shopping web application which can have items added to it. This basket might be presented to the user in a box in the top right corner of the page (see the picture below):</p>
<figure>
<img src="img/wireframe_e_commerce.png" />
</figure>
<p>The basket and its data are presented in HTML. The data and its associated View in HTML changes over time. There was a time when we used jQuery (or a similar DOM manipulation library) and a bunch of Ajax calls and callbacks to keep the two in sync. That often produced code that was not well-structured or easy to maintain. Bugs were frequent and perhaps even unavoidable.</p>
<p>The need for fast, complex, and responsive Ajax-powered web applications demands replication of a lot of this logic on the client side, dramatically increasing the size and complexity of the code residing there. Eventually this has brought us to the point where we need MVC (or a similar architecture) implemented on the client side to better structure the code and make it easier to maintain and further extend during the application life-cycle.</p>
<p>Through evolution and trial and error, JavaScript developers have harnessed the power of the traditional MVC pattern, leading to the development of several MVC-inspired JavaScript frameworks, such as Backbone.js.</p>
<h3 id="client-side-mvc---backbone-style">Client-Side MVC - Backbone Style</h3>
<p>Let’s take our first look at how Backbone.js brings the benefits of MVC to client-side development using a Todo application as our example. We will build on this example in the coming chapters when we explore Backbone’s features but for now we will just focus on the core components’ relationships to MVC.</p>
<p>Our example will need a div element to which we can attach a list of Todo’s. It will also need an HTML template containing a placeholder for a Todo item title and a completion checkbox which can be instantiated for Todo item instances. These are provided by the following HTML:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="er">&lt;</span>!doctype html&gt;
<span class="kw">&lt;html</span><span class="ot"> lang=</span><span class="st">&quot;en&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> charset=</span><span class="st">&quot;utf-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;title&gt;&lt;/title&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> name=</span><span class="st">&quot;description&quot;</span><span class="ot"> content=</span><span class="st">&quot;&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">&quot;todo&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/template&quot;</span><span class="ot"> id=</span><span class="st">&quot;item-template&quot;</span><span class="kw">&gt;</span>
&lt;div <span class="kw">class</span>=<span class="st">&quot;view&quot;</span>&gt;
&lt;input id=<span class="st">&quot;todo_complete&quot;</span> type=<span class="st">&quot;checkbox&quot;</span> &lt;%= completed ? <span class="st">&#39;checked=&quot;checked&quot;&#39;</span> : <span class="st">&#39;&#39;</span> %&gt; <span class="ot">/&gt;</span>
<span class="ot"> &lt;label&gt;&lt;%= title %&gt;&lt;/label</span>&gt;
&lt;button <span class="kw">class</span>=<span class="st">&quot;destroy&quot;</span>&gt;&lt;<span class="ot">/button&gt;</span>
<span class="ot"> &lt;/div</span>&gt;
&lt;input <span class="kw">class</span>=<span class="st">&quot;edit&quot;</span> value=<span class="st">&quot;&lt;%= title %&gt;&quot;</span>&gt;
<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;jquery.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;underscore.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;backbone.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;demo.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>In our Todo application (demo.js), Backbone Model instances are used to hold the data for each Todo item:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Define a Todo Model</span>
<span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Instantiate the Todo Model with a title, with the completed attribute</span>
<span class="co">// defaulting to false</span>
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&#39;Check attributes property of the logged models in the console.&#39;</span>
});</code></pre>
<p>Our Todo Model extends Backbone.Model and simply defines default values for two data attributes. As you will discover in the upcoming chapters, Backbone Models provide many more features but this simple Model illustrates that first and foremost a Model is a data container.</p>
<p>Each Todo instance will be rendered on the page by a TodoView:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="st">&#39;li&#39;</span>,
<span class="co">// Cache the template function for a single item.</span>
<span class="dt">todoTpl</span>: <span class="ot">_</span>.<span class="fu">template</span>( <span class="fu">$</span>(<span class="st">&#39;#item-template&#39;</span>).<span class="fu">html</span>() ),
<span class="dt">events</span>: {
<span class="st">&#39;dblclick label&#39;</span>: <span class="st">&#39;edit&#39;</span>,
<span class="st">&#39;keypress .edit&#39;</span>: <span class="st">&#39;updateOnEnter&#39;</span>,
<span class="st">&#39;blur .edit&#39;</span>: <span class="st">&#39;close&#39;</span>
},
<span class="co">// Called when the view is first created</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">$el</span> = <span class="fu">$</span>(<span class="st">&#39;#todo&#39;</span>);
<span class="co">// Later we&#39;ll look at:</span>
<span class="co">// this.listenTo(someCollection, &#39;all&#39;, this.render);</span>
<span class="co">// but you can actually run this example right now by</span>
<span class="co">// calling todoView.render();</span>
},
<span class="co">// Re-render the titles of the todo item.</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="ot">$el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">todoTpl</span>( <span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">attributes</span> ) );
<span class="co">// $el here is a reference to the jQuery element</span>
<span class="co">// associated with the view, todoTpl is a reference</span>
<span class="co">// to an Underscore template and model.attributes</span>
<span class="co">// contains the attributes of the model.</span>
<span class="co">// Altogether, the statement is replacing the HTML of</span>
<span class="co">// a DOM element with the result of instantiating a</span>
<span class="co">// template with the model&#39;s attributes.</span>
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.<span class="fu">$</span>(<span class="st">&#39;.edit&#39;</span>);
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="dt">edit</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo label is double clicked</span>
},
<span class="dt">close</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo loses focus</span>
},
<span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
<span class="co">// executed on each keypress when in todo edit mode,</span>
<span class="co">// but we&#39;ll wait for enter to get in action</span>
}
});
<span class="co">// create a view for a todo</span>
<span class="kw">var</span> todoView = <span class="kw">new</span> <span class="fu">TodoView</span>({<span class="dt">model</span>: myTodo});</code></pre>
<p>TodoView is defined by extending Backbone.View and is instantiated with an associated Model. In our example, the <code>render()</code> method uses a template to construct the HTML for the Todo item which is placed inside an li element. Each call to <code>render()</code> will replace the content of the li element using the current Model data. Thus, a View instance renders the content of a DOM element using the attributes of an associated Model. Later we will see how a View can bind its <code>render()</code> method to Model change events, causing the View to re-render whenever the Model changes.</p>
<p>So far, we have seen that Backbone.Model implements the Model aspect of MVC and Backbone.View implements the View. However, as we noted earlier, Backbone departs from traditional MVC when it comes to Controllers - there is no Backbone.Controller!</p>
<p>Instead, the Controller responsibility is addressed within the View. Recall that Controllers respond to requests and perform appropriate actions which may result in changes to the Model and updates to the View. In a single-page application, rather than having requests in the traditional sense, we have events. Events can be traditional browser DOM events (e.g., clicks) or internal application events such as Model changes.</p>
<p>In our TodoView, the <code>events</code> attribute fulfills the role of the Controller configuration, defining how events occurring within the View’s DOM element are to be routed to event-handling methods defined in the View.</p>
<p>While in this instance events help us relate Backbone to the MVC pattern, we will see them playing a much larger role in our SPA applications. Backbone.Event is a fundamental Backbone component which is mixed into both Backbone.Model and Backbone.View, providing them with rich event management capabilities. Note that the traditional controller role (Smalltalk-80 style) is performed by the template, not by the Backbone.View.</p>
<p>This completes our first encounter with Backbone.js. The remainder of this book will explore the many features which build on these simple constructs. Before moving on, let’s take a look at common features of JavaScript MV* libraries and frameworks.</p>
<h3 id="implementation-specifics">Implementation Specifics</h3>
<p>A SPA is loaded into the browser using a normal HTTP request and response. The page may simply be an HTML file, as in our example above, or it could be a view constructed by a server-side MVC implementation.</p>
<p>Once loaded, a client-side Router intercepts URLs and invokes client-side logic in place of sending a new request to the server. The picture below shows typical request handling for client-side MVC as implemented by Backbone:</p>
<figure>
<img src="img/backbone_mvc.png" />
</figure>
<p>URL routing, DOM events (e.g., mouse clicks), and Model events (e.g., attribute changes) all trigger handling logic in the View. The handlers update the DOM and Models, which may trigger additional events. Models are synced with Data Sources which may involve communicating with back-end servers.</p>
<h4 id="models">Models</h4>
<ul>
<li><p>The built-in capabilities of Models vary across frameworks. However, it’s common for them to support validation of attributes, where attributes represent the properties of the Model, such as a Model identifier.</p></li>
<li><p>When using Models in real-world applications we generally also need a way of persisting Models. Persistence allows us to edit and update Models with the knowledge that their most recent states will be saved somewhere, for example in a web browser’s localStorage data-store or synchronized with a database.</p></li>
<li><p>A Model may have multiple Views observing it for changes. By <em>observing</em> we mean that a View has registered an interest in being informed whenever an update is made to the Model. This allows the View to ensure that what is displayed on screen is kept in sync with the data contained in the model. Depending on your requirements, you might create a single View displaying all Model attributes, or create separate Views displaying different attributes. The important point is that the Model doesn’t care how these Views are organized, it simply announces updates to its data as necessary through the framework’s event system.</p></li>
<li><p>It is not uncommon for modern MVC/MV* frameworks to provide a means of grouping Models together. In Backbone, these groups are called Collections. Managing Models in groups allows us to write application logic based on notifications from the group when a Model within the group changes. This avoids the need to manually observe individual Model instances. We’ll see this in action later in the book. Collections are also useful for performing any aggregate computations across more than one model.</p></li>
</ul>
<h4 id="views">Views</h4>
<ul>
<li><p>Users interact with Views, which usually means reading and editing Model data. For example, in our Todo application, Todo Model viewing happens in the user interface in the list of all Todo items. Within it, each Todo is rendered with its title and completed checkbox. Model editing is done through an “edit” View where a user who has selected a specific Todo edits its title in a form.</p></li>
<li><p>We define a <code>render()</code> utility within our View which is responsible for rendering the contents of the <code>Model</code> using a JavaScript templating engine (provided by Underscore.js) and updating the contents of our View, referenced by <code>this.$el</code>.</p></li>
<li><p>We then add our <code>render()</code> callback as a Model subscriber, so the View can be triggered to update when the Model changes.</p></li>
<li><p>You may wonder where user interaction comes into play here. When users click on a Todo element within the View, it’s not the View’s responsibility to know what to do next. A Controller makes this decision. In Backbone, this is achieved by adding an event listener to the Todo’s element which delegates handling of the click to an event handler.</p></li>
</ul>
<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 ‘template’ into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.</p>
<p>JavaScript templating libraries (such as Mustache or Handlebars.js) are often used to define templates for Views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g ‘text/template’). Variables are delimited using a variable syntax (e.g <code>&lt;%= title %&gt;</code> for Underscore and <code>{{title}}</code> for Handlebars).</p>
<p>JavaScript template libraries typically accept data in a number of formats, including JSON; a serialisation format that is always a string. The grunt work of populating templates with data is generally taken care of by the framework itself. This has several benefits, particularly when opting to store templates externally which enables applications to load templates dynamically on an as-needed basis.</p>
<p>Let’s compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore’s ‘microtemplates’.</p>
<p><strong>Handlebars.js:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;view&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;input</span><span class="ot"> class=</span><span class="st">&quot;toggle&quot;</span><span class="ot"> type=</span><span class="st">&quot;checkbox&quot;</span> <span class="er">{{#if</span><span class="ot"> completed</span><span class="er">}}</span><span class="ot"> checked</span> <span class="er">{{/if}}</span><span class="kw">&gt;</span>
<span class="kw">&lt;label&gt;</span>{{title}}<span class="kw">&lt;/label&gt;</span>
<span class="kw">&lt;button</span><span class="ot"> class=</span><span class="st">&quot;destroy&quot;</span><span class="kw">&gt;&lt;/button&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;input</span><span class="ot"> class=</span><span class="st">&quot;edit&quot;</span><span class="ot"> value=</span><span class="st">&quot;{{title}}&quot;</span><span class="kw">&gt;</span></code></pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;view&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;input</span><span class="ot"> class=</span><span class="st">&quot;toggle&quot;</span><span class="ot"> type=</span><span class="st">&quot;checkbox&quot;</span> <span class="er">&lt;%</span><span class="ot">=</span> <span class="st">completed</span> <span class="er">?</span> <span class="er">&#39;checked&#39;</span><span class="ot"> :</span> <span class="er">&#39;&#39;</span> <span class="er">%</span><span class="kw">&gt;</span>&gt;
<span class="kw">&lt;label&gt;</span><span class="er">&lt;</span>%= title %&gt;<span class="kw">&lt;/label&gt;</span>
<span class="kw">&lt;button</span><span class="ot"> class=</span><span class="st">&quot;destroy&quot;</span><span class="kw">&gt;&lt;/button&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;input</span><span class="ot"> class=</span><span class="st">&quot;edit&quot;</span><span class="ot"> value=</span><span class="st">&quot;</span><span class="er">&lt;</span><span class="st">%= title %&gt;&quot;</span><span class="kw">&gt;</span></code></pre>
<p>You may also use double curly brackets (i.e <code>{{}}</code>) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore <code>templateSettings</code> attribute as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ot">_</span>.<span class="fu">templateSettings</span> = { <span class="dt">interpolate </span>: <span class="ot">/</span><span class="fl">\{\{(</span><span class="ot">.</span><span class="fl">+?)\}\}</span><span class="ot">/g</span> };</code></pre>
<p><strong>A note on Navigation and State</strong></p>
<p>It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn’t automatically update the URL, the role of navigation thus falls to a “router”, which assists in managing application state (e.g., allowing users to bookmark a particular view they have navigated to). As routers are 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>
<h4 id="controllers">Controllers</h4>
<p>In our Todo application, a Controller would be responsible for handling changes the user made in the edit View for a particular Todo, updating a specific Todo Model when a user has finished editing.</p>
<p>It’s with Controllers that most JavaScript MVC frameworks depart from the traditional 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 the approach didn’t translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the “proper” role of Controllers in other JavaScript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain “Controller” logic, and Routers 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 isn’t truly an MVC library. It’s in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects.</p>
<h2 id="what-does-mvc-give-us">What does MVC give us?</h2>
<p>To summarize, the MVC pattern helps you keep your application logic separate from your user interface, making it easier to change and maintain both. Thanks to this separation of logic, it is more clear where changes to your data, interface, or business logic need to be made and for what your unit tests should be written.</p>
<h3 id="delving-deeper-into-mvc">Delving Deeper into MVC</h3>
<p>Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we’ll explore it a little further.</p>
<p>The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a “set of classes to build a user interface.” In their view, it’s actually a variation of three other classical design patterns: the Observer (Publish/Subscribe), Strategy, and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I’ve covered some of these patterns in my other free book, “JavaScript Design Patterns For Beginners” if you would like to read about them further.</p>
<p>As we’ve discussed, Models represent application data, while Views handle what the user is presented on screen. As such, MVC relies on Publish/Subscribe for some of its core communication (something that surprisingly isn’t covered in many articles about the MVC pattern). When a Model is changed it “publishes” to the rest of the application that it has been updated. The “subscriber,” generally a Controller, then updates the View accordingly. The observer-viewer nature of this relationship is what facilitates multiple Views being attached to the same Model.</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’ responses to different user input and are an example of the Strategy pattern.</p>
<h3 id="summary">Summary</h3>
<p>Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.</p>
<p>When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it’s opted to approach Models, Views, Controllers or other alternatives, as this can better help you understand how the framework is intended to be used.</p>
<h3 id="further-reading">Further reading</h3>
<p>If you are interested in learning more about the variation of MVC which Backbone.js uses, please see the MVP (Model-View-Presenter) section in the appendix.</p>
<h2 id="fast-facts">Fast facts</h2>
<h3 id="backbone.js">Backbone.js</h3>
<ul>
<li>Core components: Model, View, Collection, Router. Enforces its own flavor of MV*</li>
<li>Event-driven communication between Views and Models. As we’ll see, it’s relatively straight-forward to add event listeners to any attribute in a Model, giving developers fine-grained control over what changes in the View</li>
<li>Supports data bindings through manual events or a separate Key-value observing (KVO) library</li>
<li>Support for RESTful interfaces out of the box, so Models can be easily tied to a backend</li>
<li>Extensive eventing system. It’s <a href="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’s micro-templating is available by default</li>
<li>Clear and flexible conventions for structuring applications. Backbone doesn’t force usage of all of its components and can work with only those needed</li>
</ul>
<h3 id="used-by">Used by</h3>
<p><em>Disqus</em></p>
<p>Disqus chose Backbone.js to power the latest version of its commenting widget. The Disqus team felt it was the right choice for their distributed web app, given Backbone’s small footprint and ease of extensibility.</p>
<figure>
<img src="img/disqus.png" />
</figure>
<p><em>Khan Academy</em></p>
<p>Offering a web app that aims to provide free world-class education to anyone anywhere, Khan Academy uses Backbone to keep its frontend code both modular and organized.</p>
<figure>
<img src="img/khan-academy.png" />
</figure>
<p><em>MetaLab</em></p>
<p>MetaLab created Flow, a task management app for teams using Backbone. Its workspace uses Backbone to create task views, activities, accounts, tags and more.</p>
<figure>
<img src="img/flow.png" />
</figure>
<p><em>Walmart Mobile</em></p>
<p>Walmart chose Backbone to power its mobile web applications, creating two new extension frameworks in the process - Thorax and Lumbar. We’ll be discussing both of these later in the book.</p>
<figure>
<img src="img/walmart-mobile.png" />
</figure>
<p><em>Airbnb</em></p>
<p>Airbnb developed its mobile web app using Backbone and now uses it across many of its products.</p>
<figure>
<img src="img/airbnb.png" />
</figure>
<p><em>Code School</em></p>
<p>Code School’s course challenge app is built from the ground up using Backbone, taking advantage of all the pieces it has to offer: routers, collections, models and complex event handling.</p>
<figure>
<img src="img/code-school.png" />
</figure>
<h1 id="backbone-basics">Backbone Basics</h1>
<p>In this section, you’ll learn the essentials of Backbone’s models, views, collections, events, and routers. This isn’t by any means a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications using it.</p>
<h3 id="getting-set-up">Getting set up</h3>
<p>Before we dive into more code examples, let’s define some boilerplate markup you can use to specify the dependencies Backbone requires. This boilerplate can be reused in many ways with little to no alteration and will allow you to run code from examples with ease.</p>
<p>You can paste the following into your text editor of choice, replacing the commented line between the script tags with the JavaScript from any given example:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>HTML<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> charset=</span><span class="st">&quot;UTF-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;title&gt;</span>Title<span class="kw">&lt;/title&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;http://documentcloud.github.com/underscore/underscore-min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;http://documentcloud.github.com/backbone/backbone-min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script&gt;</span>
<span class="co">// Your code goes here</span>
<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>You can then save and run the file in your browser of choice, such as Chrome or Firefox. Alternatively, if you prefer working with an online code editor, <a href="http://jsfiddle.net/jnf8B/">jsFiddle</a> and <a href="http://jsbin.com/iwiwox/1/edit">jsBin</a> versions of this boilerplate are also available.</p>
<p>Most examples can also be run directly from within the console in your browser’s developer tools, assuming you’ve loaded the boilerplate HTML page so that Backbone and its dependencies are available for use.</p>
<p>For Chrome, you can open up the DevTools via the Chrome menu in the top right hand corner: select “Tools &gt; Developer Tools” or alternatively use the Control + Shift + I shortcut on Windows/Linux or Command + Option + I on Mac.</p>
<figure>
<img src="img/devtools.png" />
</figure>
<p>Next, switch to the Console tab, from where you can enter in and run any piece of JavaScript code by hitting the return key. You can also use the Console as a multi-line editor using the Shift + Enter shortcut on Windows, or Ctrl + Enter shortcut on Mac to move from the end of one line to the start of another.</p>
<h2 id="models-1">Models</h2>
<p>Backbone models contain 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 todo item including its attributes like title (todo content) and completed (current state of the todo).</p>
<p>Models can be created by extending <code>Backbone.Model</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({});
<span class="co">// We can then create our own concrete instance of a (Todo) model</span>
<span class="co">// with no values at all:</span>
<span class="kw">var</span> todo1 = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="co">// Following logs: {}</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(todo1));
<span class="co">// or with some arbitrary data:</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&#39;Check the attributes of both model instances in the console.&#39;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// Following logs: {&quot;title&quot;:&quot;Check the attributes of both model instances in the console.&quot;,&quot;completed&quot;:true}</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(todo2));</code></pre>
<h4 id="initialization">Initialization</h4>
<p>The <code>initialize()</code> method is called when a new instance of a model is created. Its use is optional; however you’ll see why it’s good practice to use it below.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;This model has been initialized.&#39;</span>);
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="co">// Logs: This model has been initialized.</span></code></pre>
<p><strong>Default values</strong></p>
<p>There are times when you want your model to have a set of default values (e.g., in a scenario where a complete set of data isn’t provided by the user). This can be set using a property called <code>defaults</code> in your model.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Now we can create our concrete instance of the model</span>
<span class="co">// with default values as follows:</span>
<span class="kw">var</span> todo1 = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="co">// Following logs: {&quot;title&quot;:&quot;&quot;,&quot;completed&quot;:false}</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(todo1));
<span class="co">// Or we could instantiate it with some of the attributes (e.g., with custom title):</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&#39;Check attributes of the logged models in the console.&#39;</span>
});
<span class="co">// Following logs: {&quot;title&quot;:&quot;Check attributes of the logged models in the console.&quot;,&quot;completed&quot;:false}</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(todo2));
<span class="co">// Or override all of the default attributes:</span>
<span class="kw">var</span> todo3 = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&#39;This todo is done, so take no action on this one.&#39;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// Following logs: {&quot;title&quot;:&quot;This todo is done, so take no action on this one.&quot;,&quot;completed&quot;:true} </span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(todo3));</code></pre>
<h4 id="getters-setters">Getters &amp; Setters</h4>
<p><strong>Model.get()</strong></p>
<p><code>Model.get()</code> provides easy access to a model’s attributes.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo1</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>)); <span class="co">// empty string</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo1</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// false</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&quot;Retrieved with model&#39;s get() method.&quot;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo2</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>)); <span class="co">// Retrieved with model&#39;s get() method.</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo2</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// true</span></code></pre>
<p>If you need to read or clone all of a model’s data attributes, use its <code>toJSON()</code> method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When <code>JSON.stringify()</code> is passed an object with a <code>toJSON()</code> method, it stringifies the return value of <code>toJSON()</code> instead of the original object. The examples in the previous section took advantage of this feature when they called <code>JSON.stringify()</code> to log model instances.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="kw">var</span> todo1Attributes = <span class="ot">todo1</span>.<span class="fu">toJSON</span>();
<span class="co">// Following logs: {&quot;title&quot;:&quot;&quot;,&quot;completed&quot;:false} </span>
<span class="ot">console</span>.<span class="fu">log</span>(todo1Attributes);
<span class="kw">var</span> todo2 = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&quot;Try these examples and check results in console.&quot;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// logs: {&quot;title&quot;:&quot;Try these examples and check results in console.&quot;,&quot;completed&quot;:true}</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo2</span>.<span class="fu">toJSON</span>());</code></pre>
<p><strong>Model.set()</strong></p>
<p><code>Model.set()</code> sets a hash containing one or more attributes on the model. When any of these attributes alter the state of the model, a “change” event is triggered on it. Change events for each attribute are also triggered and can be bound to (e.g. <code>change:name</code>, <code>change:age</code>).</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Setting the value of attributes via instantiation</span>
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>({
<span class="dt">title</span>: <span class="st">&quot;Set through instantiation.&quot;</span>
});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Todo title: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>)); <span class="co">// Todo title: Set through instantiation.</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Completed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// Completed: false</span>
<span class="co">// Set single attribute value at a time through Model.set():</span>
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&quot;title&quot;</span>, <span class="st">&quot;Title attribute set through Model.set().&quot;</span>);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Todo title: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>)); <span class="co">// Todo title: Title attribute set through Model.set().</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Completed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// Completed: false</span>
<span class="co">// Set map of attributes through Model.set():</span>
<span class="ot">myTodo</span>.<span class="fu">set</span>({
<span class="dt">title</span>: <span class="st">&quot;Both attributes set through Model.set().&quot;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Todo title: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>)); <span class="co">// Todo title: Both attributes set through Model.set().</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Completed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// Completed: true</span></code></pre>
<p><strong>Direct access</strong></p>
<p>Models expose an <code>.attributes</code> attribute which represents an internal hash containing the state of that model. This is generally in the form of a JSON object similar to the model data you might find on the server but can take other forms.</p>
<p>Setting values through the <code>.attributes</code> attribute on a model bypasses triggers bound to the model.</p>
<p>Passing <code>{silent:true}</code> on change doesn’t delay individual <code>&quot;change:attr&quot;</code> events. Instead they are silenced entirely:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Person = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>();
<span class="ot">Person</span>.<span class="fu">on</span>(<span class="st">&quot;change:name&quot;</span>, <span class="kw">function</span>() { <span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Name changed&#39;</span>); });
<span class="ot">Person</span>.<span class="fu">set</span>({<span class="dt">name</span>: <span class="st">&#39;Andrew&#39;</span>});
<span class="co">// log entry: Name changed</span>
<span class="ot">Person</span>.<span class="fu">set</span>({<span class="dt">name</span>: <span class="st">&#39;Jeremy&#39;</span>}, {<span class="dt">silent</span>: <span class="kw">true</span>});
<span class="co">// no log entry</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">Person</span>.<span class="fu">hasChanged</span>(<span class="st">&quot;name&quot;</span>));
<span class="co">// true: change was recorded</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">Person</span>.<span class="fu">hasChanged</span>(<span class="kw">null</span>));
<span class="co">// true: something (anything) has changed</span></code></pre>
<p>Remember where possible it is best practice to use <code>Model.set()</code>, or direct instantiation as explained earlier.</p>
<h4 id="listening-for-changes-to-your-model">Listening for changes to your model</h4>
<p>If you want to receive a notification when a Backbone model changes you can bind a listener to the model for its change event. A convenient place to add listeners is in the <code>initialize()</code> function as shown below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&#39;change&#39;</span>, <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;- Values for this model have changed.&#39;</span>);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;title&#39;</span>, <span class="st">&#39;The listener is triggered whenever an attribute value changes.&#39;</span>);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Title has changed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;completed&#39;</span>, <span class="kw">true</span>);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Completed has changed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>));
<span class="ot">myTodo</span>.<span class="fu">set</span>({
<span class="dt">title</span>: <span class="st">&#39;Changing more than one attribute at the same time only triggers the listener once.&#39;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// Above logs:</span>
<span class="co">// This model has been initialized.</span>
<span class="co">// - Values for this model have changed.</span>
<span class="co">// Title has changed: The listener is triggered whenever an attribute value changes.</span>
<span class="co">// - Values for this model have changed.</span>
<span class="co">// Completed has changed: true</span>
<span class="co">// - Values for this model have changed.</span></code></pre>
<p>You can also listen for changes to individual attributes in a Backbone model. In the following example, we log a message whenever a specific attribute (the title of our Todo model) is altered.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&#39;change:title&#39;</span>, <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Title value for this model has changed.&#39;</span>);
});
},
<span class="dt">setTitle</span>: <span class="kw">function</span>(newTitle){
<span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">title</span>: newTitle });
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="co">// Both of the following changes trigger the listener:</span>
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;title&#39;</span>, <span class="st">&#39;Check what</span><span class="ch">\&#39;</span><span class="st">s logged.&#39;</span>);
<span class="ot">myTodo</span>.<span class="fu">setTitle</span>(<span class="st">&#39;Go fishing on Sunday.&#39;</span>);
<span class="co">// But, this change type is not observed, so no listener is triggered:</span>
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;completed&#39;</span>, <span class="kw">true</span>);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Todo set as completed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>));
<span class="co">// Above logs:</span>
<span class="co">// This model has been initialized.</span>
<span class="co">// Title value for this model has changed.</span>
<span class="co">// Title value for this model has changed.</span>
<span class="co">// Todo set as completed: true</span></code></pre>
<h4 id="validation">Validation</h4>
<p>Backbone supports model validation through <code>model.validate()</code>, which allows checking the attribute values for a model prior to setting them. By default, validation occurs when the model is persisted using the <code>save()</code> method or when <code>set()</code> is called if <code>{validate:true}</code> is passed as an argument.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Person = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>({<span class="dt">name</span>: <span class="st">&#39;Jeremy&#39;</span>});
<span class="co">// Validate the model name</span>
<span class="ot">Person</span>.<span class="fu">validate</span> = <span class="kw">function</span>(attrs) {
<span class="kw">if</span> (!<span class="ot">attrs</span>.<span class="fu">name</span>) {
<span class="kw">return</span> <span class="st">&#39;I need your name&#39;</span>;
}
};
<span class="co">// Change the name</span>
<span class="ot">Person</span>.<span class="fu">set</span>({<span class="dt">name</span>: <span class="st">&#39;Samuel&#39;</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">Person</span>.<span class="fu">get</span>(<span class="st">&#39;name&#39;</span>));
<span class="co">// &#39;Samuel&#39;</span>
<span class="co">// Remove the name attribute, force validation</span>
<span class="ot">Person</span>.<span class="fu">unset</span>(<span class="st">&#39;name&#39;</span>, {<span class="dt">validate</span>: <span class="kw">true</span>});
<span class="co">// false</span></code></pre>
<p>Above, we also use the <code>unset()</code> method, which removes an attribute by deleting it from the internal model attributes hash.</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, an error value should be returned instead.</p>
<p>Should an error be returned:</p>
<ul>
<li>An <code>invalid</code> event will be triggered, setting the <code>validationError</code> property on the model with the value which is returned by this method.</li>
<li><code>.save()</code> will not continue and the attributes of the model will not be modified on the server.</li>
</ul>
<p>A more complete validation example can be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">validate</span>: <span class="kw">function</span>(attributes){
<span class="kw">if</span>(<span class="ot">attributes</span>.<span class="fu">title</span> === <span class="kw">undefined</span>){
<span class="kw">return</span> <span class="st">&quot;Remember to set a title for your todo.&quot;</span>;
}
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&quot;invalid&quot;</span>, <span class="kw">function</span>(model, error){
<span class="ot">console</span>.<span class="fu">log</span>(error);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;completed&#39;</span>, <span class="kw">true</span>, {<span class="dt">validate</span>: <span class="kw">true</span>}); <span class="co">// logs: Remember to set a title for your todo.</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;completed: &#39;</span> + <span class="ot">myTodo</span>.<span class="fu">get</span>(<span class="st">&#39;completed&#39;</span>)); <span class="co">// completed: false</span></code></pre>
<p><strong>Note</strong>: the <code>attributes</code> object passed to the <code>validate</code> function represents what the attributes would be after completing the current <code>set()</code> or <code>save()</code>. This object is distinct from the current attributes of the model and from the parameters passed to the operation. Since it is created by shallow copy, it is not possible to change any Number, String, or Boolean attribute of the input within the function, but it <em>is</em> possible to change attributes in nested objects.</p>
<p>An example of this (by <span class="citation" data-cites="fivetanley">@fivetanley</span>) is available <a href="http://jsfiddle.net/2NdDY/270/">here</a>.</p>
<p>Note also, that validation on initialization is possible but of limited use, as the object being constructed is internally marked invalid but nevertheless passed back to the caller (continuing the above example):</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> emptyTodo = <span class="kw">new</span> <span class="fu">Todo</span>(<span class="kw">null</span>, {<span class="dt">validate</span>: <span class="kw">true</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">emptyTodo</span>.<span class="fu">validationError</span>);</code></pre>
<h2 id="views-1">Views</h2>
<p>Views in Backbone don’t contain the HTML markup for your application; they contain the logic behind the presentation of the model’s data to the user. This is usually achieved using JavaScript templating (e.g., Underscore Microtemplates, Mustache, jQuery-tmpl, etc.). A view’s <code>render()</code> method can be bound to a model’s <code>change()</code> event, enabling the view to instantly reflect model changes without requiring a full page refresh.</p>
<h4 id="creating-new-views">Creating new views</h4>
<p>Creating a new view is relatively straightforward and similar to creating new models. To create a new View, simply extend <code>Backbone.View</code>. We introduced the sample TodoView below in the previous chapter; now let’s take a closer look at how it works:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="st">&#39;li&#39;</span>,
<span class="co">// Cache the template function for a single item.</span>
<span class="dt">todoTpl</span>: <span class="ot">_</span>.<span class="fu">template</span>( <span class="st">&quot;An example template&quot;</span> ),
<span class="dt">events</span>: {
<span class="st">&#39;dblclick label&#39;</span>: <span class="st">&#39;edit&#39;</span>,
<span class="st">&#39;keypress .edit&#39;</span>: <span class="st">&#39;updateOnEnter&#39;</span>,
<span class="st">&#39;blur .edit&#39;</span>: <span class="st">&#39;close&#39;</span>
},
<span class="dt">initialize</span>: <span class="kw">function</span> (options) {
<span class="co">// In Backbone 1.1.0, if you want to access passed options in</span>
<span class="co">// your view, you will need to save them as follows:</span>
<span class="kw">this</span>.<span class="fu">options</span> = options || {};
},
<span class="co">// Re-render the title of the todo item.</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="ot">$el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">todoTpl</span>( <span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">attributes</span> ) );
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.<span class="fu">$</span>(<span class="st">&#39;.edit&#39;</span>);
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="dt">edit</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo label is double clicked</span>
},
<span class="dt">close</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo loses focus</span>
},
<span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
<span class="co">// executed on each keypress when in todo edit mode,</span>
<span class="co">// but we&#39;ll wait for enter to get in action</span>
}
});
<span class="kw">var</span> todoView = <span class="kw">new</span> <span class="fu">TodoView</span>();
<span class="co">// log reference to a DOM element that corresponds to the view instance</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todoView</span>.<span class="fu">el</span>); <span class="co">// logs &lt;li&gt;&lt;/li&gt;</span></code></pre>
<h4 id="what-is-el">What is <code>el</code>?</h4>
<p>The central property of a view is <code>el</code> (the value logged in the last statement of the example). What is <code>el</code> and how is it defined?</p>
<p><code>el</code> is basically a reference to a DOM element and all views must have one. Views can use <code>el</code> to compose their element’s content and then insert it into the DOM all at once, which makes for faster rendering because the browser performs the minimum required number of reflows and repaints.</p>
<p>There are two ways to associate a DOM element with a view: a new element can be created for the view and subsequently added to the DOM or a reference can be made to an element which already exists in the page.</p>
<p>If you want to create a new element for your view, set any combination of the following properties on the view: <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. If nothing is specified <code>tagName</code> defaults to <code>div</code>.</p>
<p>In the example above, <code>tagName</code> is set to ‘li’, resulting in creation of an li element. The following example creates a ul element with id and class attributes:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="st">&#39;ul&#39;</span>, <span class="co">// required, but defaults to &#39;div&#39; if not set</span>
<span class="dt">className</span>: <span class="st">&#39;container&#39;</span>, <span class="co">// optional, you can assign multiple classes to </span>
<span class="co">// this property like so: &#39;container homepage&#39;</span>
<span class="dt">id</span>: <span class="st">&#39;todos&#39;</span> <span class="co">// optional</span>
});
<span class="kw">var</span> todosView = <span class="kw">new</span> <span class="fu">TodosView</span>();
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todosView</span>.<span class="fu">el</span>); <span class="co">// logs &lt;ul id=&quot;todos&quot; class=&quot;container&quot;&gt;&lt;/ul&gt;</span></code></pre>
<p>The above code creates the DOM element below but doesn’t append it to the DOM.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;ul</span><span class="ot"> id=</span><span class="st">&quot;todos&quot;</span><span class="ot"> class=</span><span class="st">&quot;container&quot;</span><span class="kw">&gt;&lt;/ul&gt;</span></code></pre>
<p>If the element already exists in the page, you can set <code>el</code> as a CSS selector that matches the element.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">el: <span class="st">&#39;#footer&#39;</span></code></pre>
<p>Alternatively, you can set <code>el</code> to an existing element when creating the view:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todosView = <span class="kw">new</span> <span class="fu">TodosView</span>({<span class="dt">el</span>: <span class="fu">$</span>(<span class="st">&#39;#footer&#39;</span>)});</code></pre>
<p>Note: When declaring a View, <code>options</code>, <code>el</code>, <code>tagName</code>, <code>id</code> and <code>className</code> may be defined as functions, if you want their values to be determined at runtime.</p>
<p><strong><span class="math"><em>e</em><em>l</em><em>a</em><em>n</em><em>d</em></span>()</strong></p>
<p>View logic often needs to invoke jQuery or Zepto functions on the <code>el</code> element and elements nested within it. Backbone makes it easy to do so by defining the <code>$el</code> property and <code>$()</code> function. The <code>view.$el</code> property is equivalent to <code>$(view.el)</code> and <code>view.$(selector)</code> is equivalent to <code>$(view.el).find(selector)</code>. In our TodoView example’s render method, we see <code>this.$el</code> used to set the HTML of the element and <code>this.$()</code> used to find subelements of class ‘edit’.</p>
<p><strong>setElement</strong></p>
<p>If you need to apply an existing Backbone view to a different DOM element <code>setElement</code> can be used for this purpose. Overriding this.el needs to both change the DOM reference and re-bind events to the new element (and unbind from the old).</p>
<p><code>setElement</code> will create a cached <code>$el</code> reference for you, moving the delegated events for a view from the old element to the new one.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// We create two DOM elements representing buttons</span>
<span class="co">// which could easily be containers or something else</span>
<span class="kw">var</span> button1 = <span class="fu">$</span>(<span class="st">&#39;&lt;button&gt;&lt;/button&gt;&#39;</span>);
<span class="kw">var</span> button2 = <span class="fu">$</span>(<span class="st">&#39;&lt;button&gt;&lt;/button&gt;&#39;</span>);
<span class="co">// Define a new view</span>
<span class="kw">var</span> View = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">events</span>: {
<span class="dt">click</span>: <span class="kw">function</span>(e) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">view</span>.<span class="fu">el</span> === <span class="ot">e</span>.<span class="fu">target</span>);
}
}
});
<span class="co">// Create a new instance of the view, applying it</span>
<span class="co">// to button1</span>
<span class="kw">var</span> view = <span class="kw">new</span> <span class="fu">View</span>({<span class="dt">el</span>: button1});
<span class="co">// Apply the view to button2 using setElement</span>
<span class="ot">view</span>.<span class="fu">setElement</span>(button2);
<span class="ot">button1</span>.<span class="fu">trigger</span>(<span class="st">&#39;click&#39;</span>);
<span class="ot">button2</span>.<span class="fu">trigger</span>(<span class="st">&#39;click&#39;</span>); <span class="co">// returns true</span></code></pre>
<p>The “el” property represents the markup portion of the view that will be rendered; to get the view to actually render to the page, you need to add it as a new element or append it to an existing element.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// We can also provide raw markup to setElement</span>
<span class="co">// as follows (just to demonstrate it can be done):</span>
<span class="kw">var</span> view = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">View</span>;
<span class="ot">view</span>.<span class="fu">setElement</span>(<span class="st">&#39;&lt;p&gt;&lt;a&gt;&lt;b&gt;test&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;&#39;</span>);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">view</span>.<span class="fu">$</span>(<span class="st">&#39;a b&#39;</span>).<span class="fu">html</span>()); <span class="co">// outputs &quot;test&quot;</span></code></pre>
<p><strong>Understanding <code>render()</code></strong></p>
<p><code>render()</code> is an optional function that defines the logic for rendering a template. We’ll use Underscore’s micro-templating in these examples, but remember you can use other templating frameworks if you prefer. Our example will reference the following HTML markup:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="er">&lt;</span>!doctype html&gt;
<span class="kw">&lt;html</span><span class="ot"> lang=</span><span class="st">&quot;en&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> charset=</span><span class="st">&quot;utf-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;title&gt;&lt;/title&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> name=</span><span class="st">&quot;description&quot;</span><span class="ot"> content=</span><span class="st">&quot;&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">&quot;todo&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/template&quot;</span><span class="ot"> id=</span><span class="st">&quot;item-template&quot;</span><span class="kw">&gt;</span>
&lt;div&gt;
&lt;input id=<span class="st">&quot;todo_complete&quot;</span> type=<span class="st">&quot;checkbox&quot;</span> &lt;%= completed ? <span class="st">&#39;checked=&quot;checked&quot;&#39;</span> : <span class="st">&#39;&#39;</span> %&gt;&gt;
&lt;%= title %&gt;
&lt;<span class="ot">/div&gt;</span>
<span class="ot"> &lt;/script</span>&gt;
&lt;script src=<span class="st">&quot;underscore-min.js&quot;</span>&gt;<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;backbone-min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;jquery-min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;example.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>The <code>_.template</code> method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the TodoView, I’m passing the markup from the template with id <code>item-template</code> to <code>_.template()</code> to be compiled and stored in the todoTpl property when the view is created.</p>
<p>The <code>render()</code> method uses this template by passing it the <code>toJSON()</code> encoding of the attributes of the model associated with the view. The template returns its markup after using the model’s title and completed flag to evaluate the expressions containing them. I then set this markup as the HTML content of the <code>el</code> DOM element using the <code>$el</code> property.</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>A common Backbone convention is to return <code>this</code> at the end of <code>render()</code>. This is useful for a number of reasons, including:</p>
<ul>
<li>Making views easily reusable in other parent views.</li>
<li>Creating a list of elements without rendering and painting each of them individually, only to be drawn once the entire list is populated.</li>
</ul>
<p>Let’s try to implement the latter of these. The <code>render</code> method of a simple ListView which doesn’t use an ItemView for each item could be written:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> ListView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="co">// Compile a template for this view. In this case &#39;...&#39;</span>
<span class="co">// is a placeholder for a template such as </span>
<span class="co">// $(&quot;#list_template&quot;).html() </span>
<span class="dt">template</span>: <span class="ot">_</span>.<span class="fu">template</span>(…),
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="ot">$el</span>.<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">template</span>(<span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">attributes</span>));
<span class="kw">return</span> <span class="kw">this</span>;
}
});</code></pre>
<p>Simple enough. Let’s now assume a decision is made to construct the items using an ItemView to provide enhanced behaviour to our list. The ItemView could be written:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> ItemView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">events</span>: {},
<span class="dt">render</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.<span class="ot">$el</span>.<span class="fu">html</span>(<span class="kw">this</span>.<span class="fu">template</span>(<span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">attributes</span>));
<span class="kw">return</span> <span class="kw">this</span>;
}
});</code></pre>
<p>Note the usage of <code>return this;</code> at the end of <code>render</code>. This common pattern enables us to reuse the view as a sub-view. We can also use it to pre-render the view prior to rendering. Using this requires that we make a change to our ListView’s <code>render</code> method as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> ListView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">render</span>: <span class="kw">function</span>(){
<span class="co">// Assume our model exposes the items we will</span>
<span class="co">// display in our list</span>
<span class="kw">var</span> items = <span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;items&#39;</span>);
<span class="co">// Loop through each of our items using the Underscore</span>
<span class="co">// _.each iterator</span>
<span class="ot">_</span>.<span class="fu">each</span>(items, <span class="kw">function</span>(item){
<span class="co">// Create a new instance of the ItemView, passing </span>
<span class="co">// it a specific model item</span>
<span class="kw">var</span> itemView = <span class="kw">new</span> <span class="fu">ItemView</span>({ <span class="dt">model</span>: item });
<span class="co">// The itemView&#39;s DOM element is appended after it</span>
<span class="co">// has been rendered. Here, the &#39;return this&#39; is helpful</span>
<span class="co">// as the itemView renders its model. Later, we ask for </span>
<span class="co">// its output (&quot;el&quot;)</span>
<span class="kw">this</span>.<span class="ot">$el</span>.<span class="fu">append</span>( <span class="ot">itemView</span>.<span class="fu">render</span>().<span class="fu">el</span> );
}, <span class="kw">this</span>);
}
});</code></pre>
<p><strong>The <code>events</code> hash</strong></p>
<p>The Backbone <code>events</code> hash allows us to attach event listeners to either <code>el</code>-relative custom selectors, or directly to <code>el</code> if no selector is provided. An event takes the form of a key-value pair <code>'eventName selector': 'callbackFunction'</code> and a number of DOM event-types are supported, including <code>click</code>, <code>submit</code>, <code>mouseover</code>, <code>dblclick</code> and more.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// A sample view</span>
<span class="kw">var</span> TodoView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="st">&#39;li&#39;</span>,
<span class="co">// with an events hash containing DOM events</span>
<span class="co">// specific to an item:</span>
<span class="dt">events</span>: {
<span class="st">&#39;click .toggle&#39;</span>: <span class="st">&#39;toggleCompleted&#39;</span>,
<span class="st">&#39;dblclick label&#39;</span>: <span class="st">&#39;edit&#39;</span>,
<span class="st">&#39;keypress .edit&#39;</span>: <span class="st">&#39;updateOnEnter&#39;</span>,
<span class="st">&#39;click .destroy&#39;</span>: <span class="st">&#39;clear&#39;</span>,
<span class="st">&#39;blur .edit&#39;</span>: <span class="st">&#39;close&#39;</span>
},</code></pre>
<p>What isn’t instantly obvious is that while Backbone uses jQuery’s <code>.delegate()</code> underneath, it goes further by extending it so that <code>this</code> always refers to the current view object within callback functions. 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>
<p>The declarative, delegated jQuery events means that you don’t have to worry about whether a particular element has been rendered to the DOM yet or not. Usually with jQuery you have to worry about “presence or absence in the DOM” all the time when binding events.</p>
<p>In our TodoView example, the edit callback is invoked when the user double-clicks a label element within the <code>el</code> element, updateOnEnter is called for each keypress in an element with class ‘edit’, and close executes when an element with class ‘edit’ loses focus. Each of these callback functions can use <code>this</code> to refer to the TodoView object.</p>
<p>Note that you can also bind methods yourself using <code>_.bind(this.viewEvent, this)</code>, which is effectively what the value in each event’s key-value pair is doing. Below we use <code>_.bind</code> to re-render our view when a model changes.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> TodoView = <span class="ot">Backbone</span>.<span class="ot">View</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="ot">model</span>.<span class="fu">bind</span>(<span class="st">&#39;change&#39;</span>, <span class="ot">_</span>.<span class="fu">bind</span>(<span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span>));
}
});</code></pre>
<p><code>_.bind</code> only works on one method at a time, but effectively binds a function to an object so that anytime the function is called the value of <code>this</code> will be the object. <code>_.bind</code> also supports passing in arguments to the function in order to fill them in advance - a technique known as <a href="http://benalman.com/news/2012/09/partial-application-in-javascript/">partial application</a>.</p>
<h2 id="collections">Collections</h2>
<p>Collections are sets of Models and are created by extending <code>Backbone.Collection</code>.</p>
<p>Normally, when creating a collection you’ll also want to define a property specifying the type of model that your collection will contain, along with any instance properties required.</p>
<p>In the following example, we create a TodoCollection that will contain our Todo models:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>:<span class="st">&#39;Read the whole book&#39;</span>, <span class="dt">id</span>: <span class="dv">2</span>});
<span class="co">// pass array of models on collection instantiation</span>
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>([myTodo]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="ot">todos</span>.<span class="fu">length</span>); <span class="co">// Collection size: 1</span></code></pre>
<h4 id="adding-and-removing-models">Adding and Removing Models</h4>
<p>The preceding example populated the collection using an array of models when it was instantiated. After a collection has been created, models can be added and removed using the <code>add()</code> and <code>remove()</code> methods:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo
});
<span class="kw">var</span> a = <span class="kw">new</span> <span class="fu">Todo</span>({ <span class="dt">title</span>: <span class="st">&#39;Go to Jamaica.&#39;</span>}),
b = <span class="kw">new</span> <span class="fu">Todo</span>({ <span class="dt">title</span>: <span class="st">&#39;Go to China.&#39;</span>}),
c = <span class="kw">new</span> <span class="fu">Todo</span>({ <span class="dt">title</span>: <span class="st">&#39;Go to Disneyland.&#39;</span>});
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>([a,b]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="ot">todos</span>.<span class="fu">length</span>);
<span class="co">// Logs: Collection size: 2</span>
<span class="ot">todos</span>.<span class="fu">add</span>(c);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="ot">todos</span>.<span class="fu">length</span>);
<span class="co">// Logs: Collection size: 3</span>
<span class="ot">todos</span>.<span class="fu">remove</span>([a,b]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="ot">todos</span>.<span class="fu">length</span>);
<span class="co">// Logs: Collection size: 1</span>
<span class="ot">todos</span>.<span class="fu">remove</span>(c);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="ot">todos</span>.<span class="fu">length</span>);
<span class="co">// Logs: Collection size: 0</span></code></pre>
<p>Note that <code>add()</code> and <code>remove()</code> accept both individual models and lists of models.</p>
<p>Also note that when using <code>add()</code> on a collection, passing <code>{merge: true}</code> causes duplicate models to have their attributes merged in to the existing models, instead of being ignored.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> items = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>;
<span class="ot">items</span>.<span class="fu">add</span>([{ <span class="dt">id </span>: <span class="dv">1</span>, <span class="dt">name</span>: <span class="st">&quot;Dog&quot;</span> , <span class="dt">age</span>: <span class="dv">3</span>}, { <span class="dt">id </span>: <span class="dv">2</span>, <span class="dt">name</span>: <span class="st">&quot;cat&quot;</span> , <span class="dt">age</span>: <span class="dv">2</span>}]);
<span class="ot">items</span>.<span class="fu">add</span>([{ <span class="dt">id </span>: <span class="dv">1</span>, <span class="dt">name</span>: <span class="st">&quot;Bear&quot;</span> }], {<span class="dt">merge</span>: <span class="kw">true</span> });
<span class="ot">items</span>.<span class="fu">add</span>([{ <span class="dt">id </span>: <span class="dv">2</span>, <span class="dt">name</span>: <span class="st">&quot;lion&quot;</span> }]); <span class="co">// merge: false</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">JSON</span>.<span class="fu">stringify</span>(<span class="ot">items</span>.<span class="fu">toJSON</span>()));
<span class="co">// [{&quot;id&quot;:1,&quot;name&quot;:&quot;Bear&quot;,&quot;age&quot;:3},{&quot;id&quot;:2,&quot;name&quot;:&quot;cat&quot;,&quot;age&quot;:2}]</span></code></pre>
<h4 id="retrieving-models">Retrieving Models</h4>
<p>There are a few different ways to retrieve a model from a collection. The most straight-forward is to use <code>Collection.get()</code> which accepts a single id as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>:<span class="st">&#39;Read the whole book&#39;</span>, <span class="dt">id</span>: <span class="dv">2</span>});
<span class="co">// pass array of models on collection instantiation</span>
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>([myTodo]);
<span class="kw">var</span> todo2 = <span class="ot">todos</span>.<span class="fu">get</span>(<span class="dv">2</span>);
<span class="co">// Models, as objects, are passed by reference</span>
<span class="ot">console</span>.<span class="fu">log</span>(todo2 === myTodo); <span class="co">// true</span></code></pre>
<p>In client-server applications, collections contain models obtained from the server. Anytime you’re exchanging data between the client and a server, you will need a way to uniquely identify models. In Backbone, this is done using the <code>id</code>, <code>cid</code>, and <code>idAttribute</code> properties.</p>
<p>Each model in Backbone has an <code>id</code>, which is a unique identifier that is either an integer or string (e.g., a UUID). Models also have a <code>cid</code> (client id) which is automatically generated by Backbone when the model is created. Either identifier can be used to retrieve a model from a collection.</p>
<p>The main difference between them is that the <code>cid</code> is generated by Backbone; it is helpful when you don’t have a true id - this may be the case if your model has yet to be saved to the server or you aren’t saving it to a database.</p>
<p>The <code>idAttribute</code> is the identifying attribute name of the model returned from the server (i.e., the <code>id</code> in your database). This tells Backbone which data field from the server should be used to populate the <code>id</code> property (think of it as a mapper). By default, it assumes <code>id</code>, but this can be customized as needed. For instance, if your server sets a unique attribute on your model named “userId” then you would set <code>idAttribute</code> to “userId” in your model definition.</p>
<p>The value of a model’s idAttribute should be set by the server when the model is saved. After this point you shouldn’t need to set it manually, unless further control is required.</p>
<p>Internally, <code>Backbone.Collection</code> contains an array of models enumerated by their <code>id</code> property, if the model instances happen to have one. When <code>collection.get(id)</code> is called, this array is checked for existence of the model instance with the corresponding <code>id</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// extends the previous example</span>
<span class="kw">var</span> todoCid = <span class="ot">todos</span>.<span class="fu">get</span>(<span class="ot">todo2</span>.<span class="fu">cid</span>);
<span class="co">// As mentioned in previous example, </span>
<span class="co">// models are passed by reference</span>
<span class="ot">console</span>.<span class="fu">log</span>(todoCid === myTodo); <span class="co">// true</span></code></pre>
<h4 id="listening-for-events">Listening for events</h4>
<p>As collections represent a group of items, we can listen for <code>add</code> and <code>remove</code> events which occur when models are added to or removed from a collection. Here’s an example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;add&quot;</span>, <span class="kw">function</span>(todo) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;I should &quot;</span> + <span class="ot">todo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>) + <span class="st">&quot;. Have I done it before? &quot;</span> + (<span class="ot">todo</span>.<span class="fu">get</span>(<span class="st">&quot;completed&quot;</span>) ? <span class="st">&#39;Yeah!&#39;</span>: <span class="st">&#39;No.&#39;</span> ));
});
<span class="ot">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Jamaica&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to China&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to Disneyland&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="co">// The above logs:</span>
<span class="co">// I should go to Jamaica. Have I done it before? No.</span>
<span class="co">// I should go to China. Have I done it before? No.</span>
<span class="co">// I should go to Disneyland. Have I done it before? Yeah!</span></code></pre>
<p>In addition, we’re also able to bind to a <code>change</code> event to listen for changes to any of the models in the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="co">// log a message if a model in the collection changes</span>
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(model) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Changed my mind! I should &quot;</span> + <span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="ot">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span>, <span class="dt">id</span>: <span class="dv">3</span> },
]);
<span class="kw">var</span> myTodo = <span class="ot">TodosCollection</span>.<span class="fu">get</span>(<span class="dv">3</span>);
<span class="ot">myTodo</span>.<span class="fu">set</span>(<span class="st">&#39;title&#39;</span>, <span class="st">&#39;go fishing&#39;</span>);
<span class="co">// Logs: Changed my mind! I should go fishing</span></code></pre>
<p>jQuery-style event maps of the form <code>obj.on({click: action})</code> can also be used. These can be clearer than needing three separate calls to <code>.on</code> and should align better with the events hash used in Views:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> <span class="fu">Todo</span>();
<span class="ot">myTodo</span>.<span class="fu">set</span>({<span class="dt">title</span>: <span class="st">&#39;Buy some cookies&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span>});
<span class="ot">myTodo</span>.<span class="fu">on</span>({
<span class="st">&#39;change:title&#39;</span> : titleChanged,
<span class="st">&#39;change:completed&#39;</span> : stateChanged
});
<span class="kw">function</span> <span class="fu">titleChanged</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;The title was changed!&#39;</span>);
}
<span class="kw">function</span> <span class="fu">stateChanged</span>(){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;The state was changed!&#39;</span>);
}
<span class="ot">myTodo</span>.<span class="fu">set</span>({<span class="dt">title</span>: <span class="st">&#39;Get the groceries&#39;</span>});
<span class="co">// The title was changed! </span></code></pre>
<p>Backbone events also support a <a href="http://backbonejs.org/#Events-once">once()</a> method, which ensures that a callback only fires one time when a notification arrives. It is similar to Node’s <a href="http://nodejs.org/api/events.html#events_emitter_once_event_listener">once</a>, or jQuery’s <a href="http://api.jquery.com/one/">one</a>. This is particularly useful for when you want to say “the next time something happens, do this”.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Define an object with two counters</span>
<span class="kw">var</span> TodoCounter = { <span class="dt">counterA</span>: <span class="dv">0</span>, <span class="dt">counterB</span>: <span class="dv">0</span> };
<span class="co">// Mix in Backbone Events</span>
<span class="ot">_</span>.<span class="fu">extend</span>(TodoCounter, <span class="ot">Backbone</span>.<span class="fu">Events</span>);
<span class="co">// Increment counterA, triggering an event</span>
<span class="kw">var</span> incrA = <span class="kw">function</span>(){
<span class="ot">TodoCounter</span>.<span class="fu">counterA</span> += <span class="dv">1</span>;
<span class="co">// This triggering will not </span>
<span class="co">// produce any effect on the counters</span>
<span class="ot">TodoCounter</span>.<span class="fu">trigger</span>(<span class="st">&#39;event&#39;</span>);
};
<span class="co">// Increment counterB</span>
<span class="kw">var</span> incrB = <span class="kw">function</span>(){
<span class="ot">TodoCounter</span>.<span class="fu">counterB</span> += <span class="dv">1</span>;
};
<span class="co">// Use once rather than having to explicitly unbind</span>
<span class="co">// our event listener</span>
<span class="ot">TodoCounter</span>.<span class="fu">once</span>(<span class="st">&#39;event&#39;</span>, incrA);
<span class="ot">TodoCounter</span>.<span class="fu">once</span>(<span class="st">&#39;event&#39;</span>, incrB);
<span class="co">// Trigger the event for the first time</span>
<span class="ot">TodoCounter</span>.<span class="fu">trigger</span>(<span class="st">&#39;event&#39;</span>);
<span class="co">// Check out output</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">TodoCounter</span>.<span class="fu">counterA</span> === <span class="dv">1</span>); <span class="co">// true</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">TodoCounter</span>.<span class="fu">counterB</span> === <span class="dv">1</span>); <span class="co">// true</span></code></pre>
<p><code>counterA</code> and <code>counterB</code> should only have been incremented once.</p>
<h4 id="resettingrefreshing-collections">Resetting/Refreshing Collections</h4>
<p>Rather than adding or removing models individually, you might want to update an entire collection at once. <code>Collection.set()</code> takes an array of models and performs the necessary add, remove, and change operations required to update the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="ot">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">id</span>: <span class="dv">1</span>, <span class="dt">title</span>: <span class="st">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">id</span>: <span class="dv">2</span>, <span class="dt">title</span>: <span class="st">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">id</span>: <span class="dv">3</span>, <span class="dt">title</span>: <span class="st">&#39;go to Disneyland.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="co">// we can listen for add/change/remove events</span>
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;add&quot;</span>, <span class="kw">function</span>(model) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Added &quot;</span> + <span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;remove&quot;</span>, <span class="kw">function</span>(model) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Removed &quot;</span> + <span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;change:completed&quot;</span>, <span class="kw">function</span>(model) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Completed &quot;</span> + <span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="ot">TodosCollection</span>.<span class="fu">set</span>([
{ <span class="dt">id</span>: <span class="dv">1</span>, <span class="dt">title</span>: <span class="st">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> },
{ <span class="dt">id</span>: <span class="dv">2</span>, <span class="dt">title</span>: <span class="st">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">id</span>: <span class="dv">4</span>, <span class="dt">title</span>: <span class="st">&#39;go to Disney World.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> }
]);
<span class="co">// Above logs:</span>
<span class="co">// Completed go to Jamaica.</span>
<span class="co">// Removed go to Disneyland.</span>
<span class="co">// Added go to Disney World.</span></code></pre>
<p>If you need to simply replace the entire content of the collection then <code>Collection.reset()</code> can be used:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="co">// we can listen for reset events</span>
<span class="ot">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;reset&quot;</span>, <span class="kw">function</span>() {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection reset.&quot;</span>);
});
<span class="ot">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to Disneyland.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Collection size: &#39;</span> + <span class="ot">TodosCollection</span>.<span class="fu">length</span>); <span class="co">// Collection size: 3</span>
<span class="ot">TodosCollection</span>.<span class="fu">reset</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Cuba.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> }
]);
<span class="co">// Above logs &#39;Collection reset.&#39;</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&#39;Collection size: &#39;</span> + <span class="ot">TodosCollection</span>.<span class="fu">length</span>); <span class="co">// Collection size: 1</span></code></pre>
<p>Another useful tip is to use <code>reset</code> with no arguments to clear out a collection completely. This is handy when dynamically loading a new page of results where you want to blank out the current page of results.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ot">myCollection</span>.<span class="fu">reset</span>();</code></pre>
<p>Note that using <code>Collection.reset()</code> doesn’t fire any <code>add</code> or <code>remove</code> events. A <code>reset</code> event is fired instead as shown in the previous example. The reason you might want to use this is to perform super-optimized rendering in extreme cases where individual events are too expensive.</p>
<p>Also note that listening to a <a href="http://backbonejs.org/#Collection-reset">reset</a> event, the list of previous models is available in <code>options.previousModels</code>, for convenience.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todo = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>();
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>([todo])
.<span class="fu">on</span>(<span class="st">&#39;reset&#39;</span>, <span class="kw">function</span>(todos, options) {
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">options</span>.<span class="fu">previousModels</span>);
<span class="ot">console</span>.<span class="fu">log</span>([todo]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">options</span>.<span class="fu">previousModels</span>[<span class="dv">0</span>] === todo); <span class="co">// true</span>
});
<span class="ot">todos</span>.<span class="fu">reset</span>([]);</code></pre>
<p>The <code>set()</code> method available for Collections can also be used for “smart” updating of sets of models. This method attempts to perform smart updating of a collection using a specified list of models. When a model in this list isn’t present in the collection, it is added. If it’s present, its attributes will be merged. Models which are present in the collection but not in the list are removed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">
<span class="co">// Define a model of type &#39;Beatle&#39; with a &#39;job&#39; attribute</span>
<span class="kw">var</span> Beatle = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">job</span>: <span class="st">&#39;musician&#39;</span>
}
});
<span class="co">// Create models for each member of the Beatles</span>
<span class="kw">var</span> john = <span class="kw">new</span> <span class="fu">Beatle</span>({ <span class="dt">firstName</span>: <span class="st">&#39;John&#39;</span>, <span class="dt">lastName</span>: <span class="st">&#39;Lennon&#39;</span>});
<span class="kw">var</span> paul = <span class="kw">new</span> <span class="fu">Beatle</span>({ <span class="dt">firstName</span>: <span class="st">&#39;Paul&#39;</span>, <span class="dt">lastName</span>: <span class="st">&#39;McCartney&#39;</span>});
<span class="kw">var</span> george = <span class="kw">new</span> <span class="fu">Beatle</span>({ <span class="dt">firstName</span>: <span class="st">&#39;George&#39;</span>, <span class="dt">lastName</span>: <span class="st">&#39;Harrison&#39;</span>});
<span class="kw">var</span> ringo = <span class="kw">new</span> <span class="fu">Beatle</span>({ <span class="dt">firstName</span>: <span class="st">&#39;Ringo&#39;</span>, <span class="dt">lastName</span>: <span class="st">&#39;Starr&#39;</span>});
<span class="co">// Create a collection using our models</span>
<span class="kw">var</span> theBeatles = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>([john, paul, george, ringo]);
<span class="co">// Create a separate model for Pete Best</span>
<span class="kw">var</span> pete = <span class="kw">new</span> <span class="fu">Beatle</span>({ <span class="dt">firstName</span>: <span class="st">&#39;Pete&#39;</span>, <span class="dt">lastName</span>: <span class="st">&#39;Best&#39;</span>});
<span class="co">// Update the collection</span>
<span class="ot">theBeatles</span>.<span class="fu">set</span>([john, paul, george, pete]);
<span class="co">// Fires a `remove` event for &#39;Ringo&#39;, and an `add` event for &#39;Pete&#39;.</span>
<span class="co">// Updates any of John, Paul and Georges&#39;s attributes that may have</span>
<span class="co">// changed over the years.</span></code></pre>
<h4 id="underscore-utility-functions">Underscore utility functions</h4>
<p>Backbone takes full advantage of its hard dependency on Underscore by making many of its utilities directly available on collections:</p>
<p><strong><code>forEach</code>: iterate over collections</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todos = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="ot">todos</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Belgium.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="co">// iterate over models in the collection</span>
<span class="ot">todos</span>.<span class="fu">forEach</span>(<span class="kw">function</span>(model){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="co">// Above logs:</span>
<span class="co">// go to Belgium.</span>
<span class="co">// go to China.</span>
<span class="co">// go to Austria.</span></code></pre>
<p><strong><code>sortBy()</code>: sort a collection on a specific attribute</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// sort collection</span>
<span class="kw">var</span> sortedByAlphabet = <span class="ot">todos</span>.<span class="fu">sortBy</span>(<span class="kw">function</span> (todo) {
<span class="kw">return</span> <span class="ot">todo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>).<span class="fu">toLowerCase</span>();
});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="st">&quot;- Now sorted: &quot;</span>);
<span class="ot">sortedByAlphabet</span>.<span class="fu">forEach</span>(<span class="kw">function</span>(model){
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>));
});
<span class="co">// Above logs:</span>
<span class="co">// - Now sorted:</span>
<span class="co">// go to Austria.</span>
<span class="co">// go to Belgium.</span>
<span class="co">// go to China.</span></code></pre>
<p><strong><code>map()</code>: iterate through a collection, mapping each value through a transformation function</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> count = <span class="dv">1</span>;
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todos</span>.<span class="fu">map</span>(<span class="kw">function</span>(model){
<span class="kw">return</span> count++ + <span class="st">&quot;. &quot;</span> + <span class="ot">model</span>.<span class="fu">get</span>(<span class="st">&#39;title&#39;</span>);
}));
<span class="co">// Above logs:</span>
<span class="co">//1. go to Belgium.</span>
<span class="co">//2. go to China.</span>
<span class="co">//3. go to Austria.</span></code></pre>
<p><strong><code>min()</code>/<code>max()</code>: retrieve item with the min or max value of an attribute</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ot">todos</span>.<span class="fu">max</span>(<span class="kw">function</span>(model){
<span class="kw">return</span> <span class="ot">model</span>.<span class="fu">id</span>;
}).<span class="fu">id</span>;
<span class="ot">todos</span>.<span class="fu">min</span>(<span class="kw">function</span>(model){
<span class="kw">return</span> <span class="ot">model</span>.<span class="fu">id</span>;
}).<span class="fu">id</span>;</code></pre>
<p><strong><code>pluck()</code>: extract a specific attribute</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> captions = <span class="ot">todos</span>.<span class="fu">pluck</span>(<span class="st">&#39;caption&#39;</span>);
<span class="co">// returns list of captions</span></code></pre>
<p><strong><code>filter()</code>: filter a collection</strong></p>
<p><em>Filter by an array of model IDs</em></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todos = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">filterById</span>: <span class="kw">function</span>(ids){
<span class="kw">return</span> <span class="kw">this</span>.<span class="ot">models</span>.<span class="fu">filter</span>(
<span class="kw">function</span>(c) {
<span class="kw">return</span> <span class="ot">_</span>.<span class="fu">contains</span>(ids, <span class="ot">c</span>.<span class="fu">id</span>);
})
}
});</code></pre>
<p><strong><code>indexOf()</code>: return the index of a particular item within a collection</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> people = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>;
<span class="ot">people</span>.<span class="fu">comparator</span> = <span class="kw">function</span>(a, b) {
<span class="kw">return</span> <span class="ot">a</span>.<span class="fu">get</span>(<span class="st">&#39;name&#39;</span>) &lt; <span class="ot">b</span>.<span class="fu">get</span>(<span class="st">&#39;name&#39;</span>) ? -<span class="dv">1</span> : <span class="dv">1</span>;
};
<span class="kw">var</span> tom = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>({<span class="dt">name</span>: <span class="st">&#39;Tom&#39;</span>});
<span class="kw">var</span> rob = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>({<span class="dt">name</span>: <span class="st">&#39;Rob&#39;</span>});
<span class="kw">var</span> tim = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Model</span>({<span class="dt">name</span>: <span class="st">&#39;Tim&#39;</span>});
<span class="ot">people</span>.<span class="fu">add</span>(tom);
<span class="ot">people</span>.<span class="fu">add</span>(rob);
<span class="ot">people</span>.<span class="fu">add</span>(tim);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">people</span>.<span class="fu">indexOf</span>(rob) === <span class="dv">0</span>); <span class="co">// true</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">people</span>.<span class="fu">indexOf</span>(tim) === <span class="dv">1</span>); <span class="co">// true</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">people</span>.<span class="fu">indexOf</span>(tom) === <span class="dv">2</span>); <span class="co">// true</span></code></pre>
<p><strong><code>any()</code>: confirm if any of the values in a collection pass an iterator truth test</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ot">todos</span>.<span class="fu">any</span>(<span class="kw">function</span>(model){
<span class="kw">return</span> <span class="ot">model</span>.<span class="fu">id</span> === <span class="dv">100</span>;
});
<span class="co">// or</span>
<span class="ot">todos</span>.<span class="fu">some</span>(<span class="kw">function</span>(model){
<span class="kw">return</span> <span class="ot">model</span>.<span class="fu">id</span> === <span class="dv">100</span>;
});</code></pre>
<p><strong><code>size()</code>: return the size of a collection</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ot">todos</span>.<span class="fu">size</span>();
<span class="co">// equivalent to</span>
<span class="ot">todos</span>.<span class="fu">length</span>;</code></pre>
<p><strong><code>isEmpty()</code>: determine whether a collection is empty</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> isEmpty = <span class="ot">todos</span>.<span class="fu">isEmpty</span>();</code></pre>
<p><strong><code>groupBy()</code>: group a collection into groups of like items</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todos = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
<span class="ot">todos</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="st">&#39;go to Belgium.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="co">// create groups of completed and incomplete models</span>
<span class="kw">var</span> byCompleted = <span class="ot">todos</span>.<span class="fu">groupBy</span>(<span class="st">&#39;completed&#39;</span>);
<span class="kw">var</span> completed = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>(byCompleted[<span class="kw">true</span>]);
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">completed</span>.<span class="fu">pluck</span>(<span class="st">&#39;title&#39;</span>));
<span class="co">// logs: [&quot;go to Austria.&quot;]</span></code></pre>
<p>In addition, several of the Underscore operations on objects are available as methods on Models.</p>
<p><strong><code>pick()</code>: extract a set of attributes from a model</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo</span>.<span class="fu">pick</span>(<span class="st">&#39;title&#39;</span>));
<span class="co">// logs {title: &quot;go to Austria&quot;}</span></code></pre>
<p><strong><code>omit()</code>: extract all attributes from a model except those listed</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo</span>.<span class="fu">omit</span>(<span class="st">&#39;title&#39;</span>));
<span class="co">// logs {completed: false}</span></code></pre>
<p><strong><code>keys()</code> and <code>values()</code>: get lists of attribute names and values</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo</span>.<span class="fu">keys</span>());
<span class="co">// logs: [&quot;title&quot;, &quot;completed&quot;]</span>
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo</span>.<span class="fu">values</span>());
<span class="co">//logs: [&quot;go to Austria.&quot;, false]</span></code></pre>
<p><strong><code>pairs()</code>: get list of attributes as [key, value] pairs</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>});
<span class="kw">var</span> pairs = <span class="ot">todo</span>.<span class="fu">pairs</span>();
<span class="ot">console</span>.<span class="fu">log</span>(pairs[<span class="dv">0</span>]);
<span class="co">// logs: [&quot;title&quot;, &quot;go to Austria.&quot;]</span>
<span class="ot">console</span>.<span class="fu">log</span>(pairs[<span class="dv">1</span>]);
<span class="co">// logs: [&quot;completed&quot;, false]</span></code></pre>
<p><strong><code>invert()</code>: create object in which the values are keys and the attributes are values</strong></p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todo = <span class="kw">new</span> <span class="fu">Todo</span>({<span class="dt">title</span>: <span class="st">&#39;go to Austria.&#39;</span>});
<span class="ot">console</span>.<span class="fu">log</span>(<span class="ot">todo</span>.<span class="fu">invert</span>());
<span class="co">// logs: {&#39;go to Austria.&#39;: &#39;title&#39;, &#39;false&#39;: &#39;completed&#39;}</span></code></pre>
<p>The complete list of what Underscore can do can be found in its official <a href="http://documentcloud.github.com/underscore/">documentation</a>.</p>
<h4 id="chainable-api">Chainable API</h4>
<p>Speaking of utility methods, another bit of sugar in Backbone is its support for Underscore’s <code>chain()</code> method. Chaining is a common idiom in object-oriented languages; a chain is a sequence of method calls on the same object that are performed in a single statement. While Backbone makes Underscore’s array manipulation operations available as methods of Collection objects, they cannot be directly chained since they return arrays rather than the original Collection.</p>
<p>Fortunately, the inclusion of Underscore’s <code>chain()</code> method enables you to chain calls to these methods on Collections.</p>
<p>The <code>chain()</code> method returns an object that has all of the Underscore array operations attached as methods which return that object. The chain ends with a call to the <code>value()</code> method which simply returns the resulting array value. In case you haven’t seen it before, the chainable API looks like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> collection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>([
{ <span class="dt">name</span>: <span class="st">&#39;Tim&#39;</span>, <span class="dt">age</span>: <span class="dv">5</span> },
{ <span class="dt">name</span>: <span class="st">&#39;Ida&#39;</span>, <span class="dt">age</span>: <span class="dv">26</span> },
{ <span class="dt">name</span>: <span class="st">&#39;Rob&#39;</span>, <span class="dt">age</span>: <span class="dv">55</span> }
]);
<span class="kw">var</span> filteredNames = <span class="ot">collection</span>.<span class="fu">chain</span>() <span class="co">// start chain, returns wrapper around collection&#39;s models</span>
.<span class="fu">filter</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="ot">item</span>.<span class="fu">get</span>(<span class="st">&#39;age&#39;</span>) &gt; <span class="dv">10</span>; }) <span class="co">// returns wrapped array excluding Tim</span>
.<span class="fu">map</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="ot">item</span>.<span class="fu">get</span>(<span class="st">&#39;name&#39;</span>); }) <span class="co">// returns wrapped array containing remaining names</span>
.<span class="fu">value</span>(); <span class="co">// terminates the chain and returns the resulting array</span>
<span class="ot">console</span>.<span class="fu">log</span>(filteredNames); <span class="co">// logs: [&#39;Ida&#39;, &#39;Rob&#39;]</span></code></pre>
<p>Some of the Backbone-specific methods do return <code>this</code>, which means they can be chained as well:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> collection = <span class="kw">new</span> <span class="ot">Backbone</span>.<span class="fu">Collection</span>();
collection
.<span class="fu">add</span>({ <span class="dt">name</span>: <span class="st">&#39;John&#39;</span>, <span class="dt">age</span>: <span class="dv">23</span> })
.<span class="fu">add</span>({ <span class="dt">name</span>: <span class="st">&#39;Harry&#39;</span>, <span class="dt">age</span>: <span class="dv">33</span> })
.<span class="fu">add</span>({ <span class="dt">name</span>: <span class="st">&#39;Steve&#39;</span>, <span class="dt">age</span>: <span class="dv">41</span> });
<span class="kw">var</span> names = <span class="ot">collection</span>.<span class="fu">pluck</span>(<span class="st">&#39;name&#39;</span>);
<span class="ot">console</span>.<span class="fu">log</span>(names); <span class="co">// logs: [&#39;John&#39;, &#39;Harry&#39;, &#39;Steve&#39;]</span></code></pre>
<h2 id="restful-persistence">RESTful Persistence</h2>
<p>Thus far, all of our example data has been created in the browser. For most single page applications, the models are derived from a data store residing on a server. This is an area in which Backbone dramatically simplifies the code you need to write to perform RESTful synchronization with a server through a simple API on its models and collections.</p>
<p><strong>Fetching models from the server</strong></p>
<p><code>Collections.fetch()</code> retrieves a set of models from the server in the form of a JSON array by sending an HTTP GET request to the URL specified by the collection’s <code>url</code> property (which may be a function). When this data is received, a <code>set()</code> will be executed to update the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">url</span>: <span class="st">&#39;/todos&#39;</span>
});
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>();
<span class="ot">todos</span>.<span class="fu">fetch</span>(); <span class="co">// sends HTTP GET to /todos</span></code></pre>
<p><strong>Saving models to the server</strong></p>
<p>While Backbone can retrieve an entire collection of models from the server at once, updates to models are performed individually using the model’s <code>save()</code> method. When <code>save()</code> is called on a model that was fetched from the server, it constructs a URL by appending the model’s id to the collection’s URL and sends an HTTP PUT to the server. If the model is a new instance that was created in the browser (i.e., it doesn’t have an id) then an HTTP POST is sent to the collection’s URL. <code>Collections.create()</code> can be used to create a new model, add it to the collection, and send it to the server in a single method call.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">url</span>: <span class="st">&#39;/todos&#39;</span>
});
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>();
<span class="ot">todos</span>.<span class="fu">fetch</span>();
<span class="kw">var</span> todo2 = <span class="ot">todos</span>.<span class="fu">get</span>(<span class="dv">2</span>);
<span class="ot">todo2</span>.<span class="fu">set</span>(<span class="st">&#39;title&#39;</span>, <span class="st">&#39;go fishing&#39;</span>);
<span class="ot">todo2</span>.<span class="fu">save</span>(); <span class="co">// sends HTTP PUT to /todos/2</span>
<span class="ot">todos</span>.<span class="fu">create</span>({<span class="dt">title</span>: <span class="st">&#39;Try out code samples&#39;</span>}); <span class="co">// sends HTTP POST to /todos and adds to collection</span></code></pre>
<p>As mentioned earlier, a model’s <code>validate()</code> method is called automatically by <code>save()</code> and will trigger an <code>invalid</code> event on the model if validation fails.</p>
<p><strong>Deleting models from the server</strong></p>
<p>A model can be removed from the containing collection and the server by calling its <code>destroy()</code> method. Unlike <code>Collection.remove()</code> which only removes a model from a collection, <code>Model.destroy()</code> will also send an HTTP DELETE to the collection’s URL.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="ot">Backbone</span>.<span class="ot">Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="st">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="ot">Backbone</span>.<span class="ot">Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">url</span>: <span class="st">&#39;/todos&#39;</span>
});
<span class="kw">var</span> todos = <span class="kw">new</span> <span class="fu">TodosCollection</span>();