Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tree: 49a930027b
Fetching contributors…

Cannot retrieve contributors at this time

8272 lines (7266 sloc) 760.01 kB
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Developing Backbone.js Applications - </title>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
q { quotes: "" "" "" ""; }
</style>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > 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><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="#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-mvp-backbone.js">MVC, MVP &amp; Backbone.js</a></li>
<li><a href="#mvc">MVC</a><ul>
<li><a href="#smalltalk-80-mvc">Smalltalk-80 MVC</a></li>
</ul></li>
<li><a href="#mvc-as-we-know-it">MVC As We Know It</a><ul>
<li><a href="#models">Models</a></li>
<li><a href="#views">Views</a></li>
<li><a href="#controllers">Controllers</a></li>
<li><a href="#controllers-in-spine.js-vs-backbone.js">Controllers in Spine.js vs Backbone.js</a></li>
</ul></li>
<li><a href="#what-does-mvc-give-us">What does MVC give us?</a><ul>
<li><a href="#delving-deeper">Delving deeper</a></li>
<li><a href="#summary">Summary</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="#fast-facts">Fast facts</a><ul>
<li><a href="#backbone.js">Backbone.js</a></li>
</ul></li>
</ul></li>
<li><a href="#the-internals">The Internals</a><ul>
<li><a href="#models-1">Models</a><ul>
<li><a href="#initialization">Initialization</a></li>
<li><a href="#getters-setters">Getters &amp; Setters</a></li>
<li><a href="#listening-for-changes-to-your-model">Listening for changes to your model</a></li>
<li><a href="#validation">Validation</a></li>
</ul></li>
<li><a href="#views-1">Views</a><ul>
<li><a href="#creating-new-views">Creating new views</a></li>
<li><a href="#what-is-el">What is <code>el</code>?</a></li>
</ul></li>
<li><a href="#collections">Collections</a><ul>
<li><a href="#underscore-utility-functions">Underscore utility functions</a></li>
<li><a href="#chainable-api">Chainable API</a></li>
</ul></li>
<li><a href="#events">Events</a></li>
<li><a href="#routers">Routers</a><ul>
<li><a href="#is-there-a-limit-to-the-number-of-routers-i-should-be-using">Is there a limit to the number of routers I should be using?</a></li>
<li><a href="#backbone.history">Backbone.history</a></li>
<li><a href="#backbones-sync-api">Backbone’s Sync API</a></li>
<li><a href="#conflict-management">Conflict Management</a></li>
</ul></li>
<li><a href="#inheritance-mixins">Inheritance &amp; Mixins</a><ul>
<li><a href="#backbone-super">Backbone-Super</a></li>
</ul></li>
<li><a href="#dependencies">Dependencies</a><ul>
<li><a href="#dom-manipulation">DOM Manipulation</a></li>
<li><a href="#utilities">Utilities</a></li>
<li><a href="#restful-persistence">RESTFul persistence</a></li>
<li><a href="#routing">Routing</a></li>
</ul></li>
<li><a href="#namespacing">Namespacing</a><ul>
<li><a href="#what-is-namespacing">What is namespacing?</a></li>
</ul></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="#index">Index</a></li>
<li><a href="#application-html">Application 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="#setup">Setup</a></li>
<li><a href="#in-action">In action</a></li>
<li><a href="#templates">Templates</a></li>
<li><a href="#in-action-1">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="#conclusions">Conclusions</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="#part-1">Part 1</a><ul>
<li><a href="#setting-up">Setting up</a></li>
</ul></li>
<li><a href="#part-2">Part 2</a><ul>
<li><a href="#adding-models">Adding models</a></li>
<li><a href="#removing-models">Removing models</a></li>
<li><a href="#summary-1">Summary</a></li>
</ul></li>
<li><a href="#part-2.5">Part 2.5</a><ul>
<li><a href="#installing-node-modules">Installing node modules</a></li>
<li><a href="#create-directory-structure">Create directory structure</a></li>
<li><a href="#create-a-simple-web-server">Create a simple web server</a></li>
<li><a href="#connect-to-database">Connect to database</a></li>
</ul></li>
<li><a href="#part-3">Part 3</a><ul>
<li><a href="#summary-2">Summary</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">Backbone Boilerplate</a></li>
<li><a href="#grunt-bbb">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="#conclusions-1">Conclusions</a></li>
<li><a href="#related-tools-projects">Related Tools &amp; Projects</a></li>
</ul></li>
<li><a href="#common-problems-solutions">Common Problems &amp; Solutions</a><ul>
<li><a href="#nesting-what-is-the-best-approach-for-rendering-and-appending-sub-views-in-backbone.js">Nesting: What is the best approach for rendering and appending Sub-Views in Backbone.js?</a></li>
<li><a href="#what-is-the-best-way-to-manage-models-in-nested-views">What is the best way to manage models in nested Views?</a></li>
<li><a href="#is-it-possible-to-have-one-backbone.js-view-trigger-updates-in-other-views">Is it possible to have one Backbone.js View trigger updates in other Views?</a></li>
<li><a href="#how-would-one-render-a-parent-view-from-one-of-its-children">How would one render a Parent View from one of its Children?</a></li>
<li><a href="#how-do-you-cleanly-dispose-views-to-avoid-memory-leaks">How do you cleanly dispose Views to avoid memory leaks?</a></li>
<li><a href="#how-does-one-handle-view-disposal-on-a-parent-or-child-view">How does one handle View disposal on a Parent or Child View?</a></li>
<li><a href="#whats-the-best-way-to-combine-or-append-views-to-each-other">What’s the best way to combine or append Views to each other?</a></li>
<li><a href="#better-model-property-validation">Better Model Property Validation</a></li>
</ul></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="#writing-amd-modules-with-requirejs">Writing AMD modules with RequireJS</a><ul>
<li><a href="#alternate-syntax">Alternate syntax</a></li>
</ul></li>
</ul></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>
<li><a href="#optimize-and-build-a-backbone.js-javascript-application-with-requirejs-using-packages">Optimize and Build a Backbone.js JavaScript application with RequireJS using Packages</a><ul>
<li><a href="#file-organization">File organization</a></li>
<li><a href="#build-profile-to-optimize-modular-dependencies-with-code-organized-in-packages">Build profile to optimize modular dependencies with code organized in packages</a></li>
<li><a href="#a-quick-note-on-code-standards">A quick note on code standards</a></li>
<li><a href="#common-pitfall-when-organizing-code-in-modules">Common Pitfall when organizing code in modules</a></li>
<li><a href="#executing-the-build-with-r.js">Executing the Build with r.js</a></li>
</ul></li>
<li><a href="#exercise-building-a-modular-backbone-app-with-amd-requirejs">Exercise: Building a modular Backbone app with AMD &amp; RequireJS</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>
</ul></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="#decoupling-backbone-with-the-mediator-and-facade-patterns">Decoupling Backbone with the Mediator and Facade Patterns</a><ul>
<li><a href="#summary-3">Summary</a></li>
<li><a href="#exercise">Exercise</a></li>
</ul></li>
<li><a href="#backbone.marionette">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><ul>
<li><a href="#controllers-1">Controllers</a></li>
<li><a href="#compositeview">CompositeView</a></li>
</ul></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="#paginating-backbone.js-requests-collections">Paginating Backbone.js Requests &amp; Collections</a></li>
<li><a href="#paginators-pieces">Paginator’s pieces</a></li>
<li><a href="#live-examples">Live Examples</a></li>
<li><a href="#paginator.requestpager">Paginator.requestPager</a><ul>
<li><a href="#create-a-new-paginated-collection">1. Create a new Paginated collection</a></li>
<li><a href="#set-the-model-for-the-collection-as-normal">2: Set the model for the collection as normal</a></li>
<li><a href="#configure-the-base-url-and-the-type-of-the-request">3. Configure the base URL and the type of the request</a></li>
<li><a href="#configure-how-the-library-will-show-the-results">4. Configure how the library will show the results</a></li>
<li><a href="#configure-the-parameters-we-want-to-send-to-the-server">5. Configure the parameters we want to send to the server</a></li>
<li><a href="#finally-configure-collection.parse-and-were-done">6. Finally, configure Collection.parse() and we’re done</a></li>
<li><a href="#convenience-methods">Convenience methods:</a></li>
</ul></li>
<li><a href="#paginator.clientpager">Paginator.clientPager</a><ul>
<li><a href="#create-a-new-paginated-collection-with-a-model-and-url">1. Create a new paginated collection with a model and URL</a></li>
<li><a href="#configure-the-base-url-and-the-type-of-the-request-1">2. Configure the base URL and the type of the request</a></li>
<li><a href="#configure-how-the-library-will-show-the-results-1">3. Configure how the library will show the results</a></li>
<li><a href="#configure-the-parameters-we-want-to-send-to-the-server-1">4. Configure the parameters we want to send to the server</a></li>
<li><a href="#finally-configure-collection.parse-and-were-done-1">5. Finally, configure Collection.parse() and we’re done</a></li>
<li><a href="#convenience-methods-1">Convenience methods:</a></li>
<li><a href="#implementation-notes">Implementation notes:</a></li>
</ul></li>
<li><a href="#plugins">Plugins</a></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="#mobile-applications">Mobile Applications</a><ul>
<li><a href="#backbone-jquery-mobile">Backbone &amp; jQuery Mobile</a><ul>
<li><a href="#resolving-the-routing-conflicts">Resolving the routing conflicts</a></li>
<li><a href="#exercise-a-backbone-require.jsamd-app-with-jquery-mobile">Exercise: A Backbone, Require.js/AMD app with jQuery Mobile</a></li>
<li><a href="#getting-started-1">Getting started</a></li>
<li><a href="#jquery-mobile-going-beyond-mobile-application-development">jQuery Mobile: Going beyond mobile application development</a></li>
</ul></li>
</ul></li>
<li><a href="#unit-testing">Unit Testing</a><ul>
<li><a href="#unit-testing-backbone-applications-with-jasmine">Unit Testing Backbone Applications With Jasmine</a></li>
<li><a href="#introduction-2">Introduction</a></li>
<li><a href="#jasmine">Jasmine</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-setup">Getting setup</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></li>
<li><a href="#initial-setup">Initial setup</a></li>
<li><a href="#view-rendering">View rendering</a></li>
<li><a href="#rendering-with-a-templating-system">Rendering with a templating system</a></li>
<li><a href="#conclusions-2">Conclusions</a></li>
<li><a href="#exercise-1">Exercise</a></li>
<li><a href="#further-reading">Further reading</a></li>
<li><a href="#unit-testing-backbone-applications-with-qunit-and-sinonjs">Unit Testing Backbone Applications With QUnit And SinonJS</a></li>
<li><a href="#introduction-3">Introduction</a></li>
</ul></li>
<li><a href="#qunit">QUnit</a><ul>
<li><a href="#getting-setup-1">Getting Setup</a><ul>
<li><a href="#sample-html-with-qunit-compatible-markup">Sample HTML with QUnit-compatible markup:</a></li>
</ul></li>
<li><a href="#assertions">Assertions</a><ul>
<li><a href="#basic-test-case-using-test-name-callback">Basic test case using test( name, callback ):</a></li>
<li><a href="#comparing-the-actual-output-of-a-function-against-the-expected-output">Comparing the actual output of a function against the expected output:</a></li>
</ul></li>
<li><a href="#adding-structure-to-assertions">Adding structure to assertions</a><ul>
<li><a href="#basic-qunit-modules">Basic QUnit Modules:</a></li>
<li><a href="#using-setup-and-teardown">Using setup() and teardown() :</a></li>
<li><a href="#using-setup-and-teardown-for-instantiation-and-clean-up">Using setup() and teardown() for instantiation and clean-up:</a></li>
</ul></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="#fixture-markup">Fixture markup:</a></li>
<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><ul>
<li><a href="#basic-spies">Basic Spies:</a></li>
<li><a href="#spying-on-existing-functions">Spying On Existing Functions:</a></li>
<li><a href="#matching-arguments-test-a-spy-was-called-with-a-specific-set-of-arguments">Matching arguments: test a spy was called with a specific set of arguments:</a></li>
<li><a href="#stricter-argument-matching-test-a-spy-was-called-at-least-once-with-specific-arguments-and-no-others">Stricter argument matching: test a spy was called at least once with specific arguments and no others:</a></li>
<li><a href="#testing-call-order-testing-if-a-spy-was-called-before-or-after-another-spy">Testing call order: testing if a spy was called before or after another spy:</a></li>
<li><a href="#match-execution-counts-test-a-spy-was-called-a-specific-number-of-times">Match execution counts: test a spy was called a specific number of times:</a></li>
</ul></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-2">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="#event">Event</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><ul>
<li><a href="#notes">Notes</a></li>
</ul></li>
</ul>
</nav>
<h2 id="prelude"><a href="#TOC">Prelude</a></h2>
<figure>
<img src="img/logo.jpg"><figcaption></figcaption>
</figure>
<p>Welcome to my (in-progress) book about the <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> library for structuring JavaScript applications. It’s released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">license</a> meaning you can both grab a copy of the book for free or help to further <a href="https://github.com/addyosmani/backbone-fundamentals/">improve</a> it.</p>
<p>I’m very pleased to announce that this book will be out in physical form (once complete) via <a href="http://oreilly.com">O’Reilly Media</a>. Readers will have the option of purchasing the latest version in either print or a number of digital formats then or can grab a recent version from this repository.</p>
<p>Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help. My extended thanks go out to <a href="https://github.com/jashkenas">Jeremy Ashkenas</a> for creating Backbone.js and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">these</a> members of the community for their assistance tweaking this project.</p>
<p>I hope you find this book helpful!</p>
<h1 id="introduction"><a href="#TOC">Introduction</a></h1>
<p>When writing a web application from scratch, it’s easy to feel like we can get by simply by relying on a DOM manipulation library (like jQuery) and a handful of utility plugins. The problem with this is that it doesn’t take long to get lost in a nested pile of jQuery callbacks and DOM elements without any real structure in place for our applications.</p>
<p>In short, we’re stuck with spaghetti code. Fortunately there are modern JavaScript frameworks and libraries that can assist with bringing structure and organization to our projects, improving how easily maintainable they are in the long-run.</p>
<h3 id="what-is-mvc"><a href="#TOC">What Is MVC?</a></h3>
<p>These modern tools 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 down into three parts:</p>
<ul>
<li>Models represent the domain-specific knowledge and data in an application. Think of this as being a <q>type</q> of data you can model — like a User, Photo or Todo note. Models should notify anyone observing them about their current state (e.g Views).</li>
<li>Views are typically considered the User-interface in an application (e.g your markup and templates), but don’t have to be. They should know about the existence of Models in order to observe them, but don’t directly communicate with them.</li>
<li>Controllers handle the input (e.g clicks, user actions) in an application and Views can be considered as handling the output. When a Controller updates the state of a model (such as editing Todo note content), it doesn’t directly tell the View. This is what the observing nature of the View and Model relationship is for.</li>
</ul>
<p>JavaScript <q>MVC</q> frameworks that can help us structure our code don’t always strictly follow the above pattern. Some solutions will include the responsibility of the Controller in the View (e.g Backbone.js) whilst others add their own opinionated components into the mix as they feel this is more effective.</p>
<p>For this reason we refer to such frameworks as following the MV* pattern, that is, you’re likely to have a View and a Model, but more likely to have something else also included.</p>
<h3 id="what-is-backbone.js"><a href="#TOC">What is Backbone.js?</a></h3>
<figure>
<img src="img/backbonejsorg.png"><figcaption></figcaption>
</figure>
<p>Backbone.js is a lightweight JavaScript library for adding 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 or SPAs. To put it simply, these apps enable the browser to react to changes in data on the client-side without the need to completely load up all your markup from the server, meaning no complete page-refreshes are necessary.</p>
<p>Backbone.js is a mature, popular library at the time of writing and has both a large development community online as well as a wealth of plugins and extensions available to build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and Foursquare.</p>
<h3 id="when-do-i-need-a-javascript-mvc-framework"><a href="#TOC">When Do I Need A JavaScript MVC Framework?</a></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, such as Backbone.js.</p>
<p>At the outset, it isn’t terribly difficult to write an application framework that offers some opinionated way to avoid spaghetti code, however to say that it is equally as trivial to write something of the standard of 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 not only include many of 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 that will likely only be communicating with an API or back-end data service, where much of the heavy lifting for viewing or manipulating that data will be occurring in the browser, you may find a JavaScript MV* framework useful. Good examples of applications that fall into this category are GMail and Google Docs.</p>
<p>These 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. It’s trivial to switch between reading an email or document to writing one and you don’t need to ask the application to render the whole page again at all.</p>
<p>If, however, you’re building an application that still relies on the server for most of the heavy-lifting of Views/pages and you’re just using a little JavaScript or jQuery to make things a little 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"><a href="#TOC">Why Consider Backbone.js?</a></h3>
<p>Does the following describe you?:</p>
<p>&quot;I want something flexible which offers a minimalist solution to separating concerns in my application. It should support a persistence layer and RESTful sync, models, views (with controllers), event-driven communication, templating and routing. It should be imperative, allowing one to update the View when a model changes. I’d like some decisions about the architecture left up to me. Ideally, many large companies have used the solution to build non-trivial applications.</p>
<p>As I may be building something complex, I’d like there to be an active extension community around the framework that have already tried addressing larger problems (Marionette, Chaplin, Aura, Thorax). Ideally, there are also scaffolding tools (grunt-bbb, brunch) available for the solution.&quot;</p>
<p>If so, continue reading.</p>
<p>Backbone’s main benefits, regardless of your target platform or device, include helping:</p>
<ul>
<li>Organize the structure to your application</li>
<li>Simplify server-side persistence</li>
<li>Decouple the DOM from your page’s data</li>
<li>Model data, views and routers in a succinct manner</li>
<li>Provide DOM, model and collection synchronization</li>
</ul>
<h3 id="setting-expectations"><a href="#TOC">Setting Expectations</a></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 a pull-request. It won’t take long and you’ll be helping other developers avoid problems you’ve run into before.</p>
<p>Topics will include MVC theory and how to build applications using Backbone’s models, views, collections and routers. I’ll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), how to build applications using modern software stacks (like Node and Express), how to solve the routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and a lot more.</p>
<h1 id="fundamentals"><a href="#TOC">Fundamentals</a></h1>
<p>In this section, we’re going to explore how frameworks like Backbone.js fit in the world of JavaScript application architecture. Classically, 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 come to client-side development.</p>
<p>Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns.</p>
<h3 id="mvc-mvp-backbone.js"><a href="#TOC">MVC, MVP &amp; Backbone.js</a></h3>
<p>Design patterns are proven solutions to common development problems and can suggest structural approaches to help guide developers in adding some organization to their applications.</p>
<p>Patterns are useful because they’re a set of practices that build upon the collective experience of skilled developers who have repeatedly solved similar problems. Although developers 10 or 20 years ago may not have been using the same programming languages when implementing patterns in their projects, there are many lessons we can learn from their efforts.</p>
<p>In this section, we’re going to review two popular patterns - MVC and MVP. We’ll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in.</p>
<h2 id="mvc"><a href="#TOC">MVC</a></h2>
<p>MVC (Model-View-Controller) is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally present to manage logic, user-input and the coordination of models and views. The pattern was originally designed by <a href="http://en.wikipedia.org/wiki/Trygve_Reenskaug">Trygve Reenskaug</a> while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in <a href="http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612"><q>Design Patterns: Elements of Reusable Object-Oriented Software</q></a> (The <q>GoF</q> or <q>Gang of Four</q> book) in 1994, which played a role in popularizing its use.</p>
<h3 id="smalltalk-80-mvc"><a href="#TOC">Smalltalk-80 MVC</a></h3>
<p>It’s important to understand what the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70’s, graphical user-interfaces were 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 were ignorant of the user-interface (Views and Controllers)</li>
<li>Presentation was taken care of by the View and the Controller, but there wasn’t just a single view and controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them</li>
<li>The Controller’s role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.</li>
<li>The Observer pattern was relied upon for updating the View whenever the Model changed</li>
</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 Models should result in the View being refreshed instantly.</p>
<p>Martin Fowler has done an excellent job of writing about the <a href="http://martinfowler.com/eaaDev/uiArchs.html">origins</a> of MVC over the years and if you are interested in further historical information about Smalltalk-80’s MVC, I recommend reading his work.</p>
<h2 id="mvc-as-we-know-it"><a href="#TOC">MVC As We Know It</a></h2>
<p>We’ve reviewed the 70’s, but let us now return to the here and now. The MVC pattern has been applied to a diverse range of programming languages. For example, the popular Ruby on Rails is an implementation of a web application framework based on MVC for the Ruby language. JavaScript now has a number of MVC frameworks, including AngularJS - a framework that extends HTML and JavaScript for dynamic content needs and of course Backbone.js. Given the importance of avoiding <q>spaghetti</q> code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let’s look at what the MVC pattern enables the Javascript developer to do.</p>
<p>MVC is composed of three core components:</p>
<h3 id="models"><a href="#TOC">Models</a></h3>
<p>Models manage the data for an application. They are concerned with neither the user-interface nor presentation layers, but instead represent structured data that an application may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has occurred so that they may react accordingly.</p>
<p>To understand models better, let us imagine we have a JavaScript todo application. In a todo app, a todo item would merit its own model, as it represents a unique kind of domain-specific data. The Todo model may represent attributes such as a title and completed. A specific todo would be stored in an instance of a model. Here’s an example of a simple Todo model implemented with Backbone.js:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default attributes for the todo</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// todo instantiated with default attributes </span>
<span class="kw">var</span> firstTodo = <span class="kw">new</span> Todo();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Todo&#39;s default title: &quot;</span> + <span class="kw">firstTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>)); <span class="co">// &quot;&quot;</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Todo&#39;s default status: &quot;</span> + <span class="kw">firstTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>)); <span class="co">// false</span>
<span class="kw">firstTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;title&#39;</span>, <span class="ch">&#39;Enjoy reading the book&#39;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Title changed: &#39;</span> + <span class="kw">firstTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="co">// new todo instantiated with todo specific data</span>
<span class="kw">var</span> secondTodo = <span class="kw">new</span> Todo({ <span class="dt">title</span>: <span class="ch">&#39;Try this code in chrome console&#39;</span>});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Second todo title: &quot;</span> + <span class="kw">secondTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Second todo status: &quot;</span> + <span class="kw">secondTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));</code></pre>
<p>The built-in capabilities of models vary across frameworks, however it’s common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also need a way of persisting models. Persistence allows us to edit and update models with the knowledge that their most recent states will be saved somewhere, for example in a web browser’s localStorage data-store or synchronized with a database.</p>
<p>A model may also have multiple views observing it. Imagine our Todo model contained meta-data such as the scheduled date, notes, days on which to repeat (if it’s something we do on regular basis). A developer could create a single view that displayed all these attributes, or might create three separate views to display each attribute. The important detail is that the Todo model doesn’t care how these views are organized, it simply announces updates to its data as necessary. We’ll come back to Views in more detail later.</p>
<p>It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called <q>Collections</q>. Managing models in groups allows us to write application logic based on notifications from the group, should any model it contains change. This avoids the need to manually observe individual model instances.</p>
<p>Here’s how we might group Todo models into a Backbone Collection:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default attributes for the todo</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> Todos = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="co">// For simplicity we&#39;ll use localStorage throughout the first part of book.</span>
<span class="co">// Save all of the todo items under the `&quot;todos&quot;` namespace.</span>
<span class="dt">localStorage</span>: <span class="kw">new</span> Store(<span class="ch">&#39;todos-backbone&#39;</span>)
<span class="co">// When working with REST API on back-end here would be</span>
<span class="co">// appropriate to use:</span>
<span class="co">// url: &quot;/todos&quot;</span>
});
<span class="kw">var</span> firstTodo = <span class="kw">new</span> Todo({<span class="dt">title</span>:<span class="ch">&#39;Read whole book&#39;</span>});
<span class="co">// pass array of models on collection instantiation</span>
<span class="kw">var</span> todos = <span class="kw">new</span> Todos([firstTodo]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todos</span>.<span class="fu">length</span>);
<span class="co">// Collection&#39;s convenience method used to create </span>
<span class="co">// new model instance within collection itself.</span>
<span class="kw">todos</span>.<span class="fu">create</span>({<span class="dt">title</span>:<span class="ch">&#39;Try out code examples&#39;</span>});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todos</span>.<span class="fu">length</span>);
<span class="kw">var</span> thirdTodo = <span class="kw">new</span> Todo({<span class="dt">title</span>:<span class="ch">&#39;Make something cool&#39;</span>});
<span class="co">// Adds model to collection</span>
<span class="kw">todos</span>.<span class="fu">add</span>(thirdTodo);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todos</span>.<span class="fu">length</span>);
<span class="co">// Collection keeps models in models </span>
<span class="co">// property which is an array.</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todos</span>.<span class="fu">models</span>);</code></pre>
<p>If you read older texts on MVC, you may come across a description of models as also managing application <q>state</q>. In JavaScript applications state has a specific meaning, typically referring to the current state of a view or sub-view on a user’s screen at a fixed time. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated.</p>
<h3 id="views"><a href="#TOC">Views</a></h3>
<p>Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, allowing the view to update itself accordingly. Design pattern literature commonly refers to views as <q>dumb</q>, given that their knowledge of models and controllers in an application is limited.</p>
<p>Users interact with views, which usually means reading and editing model data. For example, in our todo application example, todo model viewing might happen in a user interface in the list of all todo items. Within it each todo is rendered with their title and completed checkbox. Model editing could be done through an <q>edit</q> view where a user who has selected a specific todo could edit its title in a form.</p>
<p>In MVC, the actual task of updating the Model falls to Controllers, which we’ll be covering shortly.</p>
<p>Let’s explore Views a little further using a simple JavaScript example. Below we can see a function that creates a single Todo view, consuming both a model instance and a controller instance.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> buildTodoView = <span class="kw">function</span> ( todoModel, todoController ) {
<span class="kw">var</span> base = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>),
todoEl = <span class="kw">document</span>.<span class="fu">createElement</span>(<span class="ch">&#39;div&#39;</span>);
<span class="kw">base</span>.<span class="fu">appendChild</span>(todoEl);
<span class="kw">var</span> render= <span class="kw">function</span>(){
<span class="co">// We use a templating library such as Underscore</span>
<span class="co">// templating which generates the HTML for our</span>
<span class="co">// todo entry</span>
<span class="kw">todoEl</span>.<span class="fu">innerHTML</span> = <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#todoTemplate&#39;</span>).<span class="fu">html</span>(), { <span class="dt">src</span>: <span class="kw">todoModel</span>.<span class="fu">getSrc</span>() });
}
<span class="kw">todoModel</span>.<span class="fu">addSubscriber</span>( render );
<span class="kw">todoEl</span>.<span class="fu">addEventListener</span>(<span class="ch">&#39;click&#39;</span>, <span class="kw">function</span>(){
<span class="kw">todoController</span>.<span class="fu">handleEvent</span>(<span class="ch">&#39;click&#39;</span>, todoModel );
});
<span class="kw">var</span> show = <span class="kw">function</span>(){
<span class="kw">todoEl.style</span>.<span class="fu">display</span> = <span class="ch">&#39;&#39;</span>;
}
<span class="kw">var</span> hide = <span class="kw">function</span>(){
<span class="kw">todoEl.style</span>.<span class="fu">display</span> = <span class="ch">&#39;none&#39;</span>;
}
<span class="kw">return</span> {
<span class="dt">showView</span>: show,
<span class="dt">hideView</span>: hide
}
}</code></pre>
<p>We define a <code>render()</code> utility within our view which is responsible for rendering the contents of the <code>todoModel</code> using a JavaScript templating engine (<a href="http://underscorejs.org" title="Underscore.js">Underscore</a> templating) and updating the contents of our view, referenced by <code>todoEl</code>.</p>
<p>The <code>todoModel</code> then adds our <code>render()</code> callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes.</p>
<p>You may wonder where user interaction comes into play here. When users click on any elements within the view, it’s not the view’s responsibility to know what to do next. A Controller makes this decision. In our sample implementation, this is achieved by adding an event listener to <code>todoEl</code> which will delegate handling the click behavior back to the controller, passing the model information along with it in case it’s needed.</p>
<p>The benefit of this architecture is that each component plays its own separate role in making the application function as needed.</p>
<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 <q>template</q> into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.</p>
<p>JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to define templates for views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g <q>text/template</q>). Variables are delimited using a variable syntax (e.g {{title}}). Javascript template libraries typically accept data in JSON, and the grunt work of populating templates with data is taken care of by the framework itself. This has a several benefits, particularly when opting to store templates externally as this can let applications load templates dynamically on an as-needed basis.</p>
<p>Let’s compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore’s <q>microtemplates</q>.</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="er">&quot;checked&quot;</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="st">?</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="kw">_</span>.<span class="fu">templateSettings</span> = { <span class="dt">interpolate </span>: <span class="ot">/</span><span class="fl">\{\{(</span><span class="ot">.</span><span class="fl">+?)\}\}</span><span class="ot">/g</span> };</code></pre>
<p><strong>A note on navigation and state</strong></p>
<p>It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn’t automatically update the URL, the role of navigation thus falls to a <q>router</q>, which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.</p>
<h3 id="controllers"><a href="#TOC">Controllers</a></h3>
<p>Controllers are an intermediary between models and views which are classically responsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view.</p>
<p>In our 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 this interpretation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript framework authors likely initially looked at server-side interpretations of MVC (such as Ruby on Rails), realized that that approach didn’t translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the <q>proper</q> role of controllers in other JavaScript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain <q>controller</q> logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC.</p>
<p>In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is not a true MVC framework. It’s in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects.</p>
<h3 id="controllers-in-spine.js-vs-backbone.js"><a href="#TOC">Controllers in Spine.js vs Backbone.js</a></h3>
<p><strong>Spine.js</strong></p>
<p>We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). Since Backbone doesn’t have its <strong>own</strong> explicit controllers, it’s useful to review the controller from another MVC framework to appreciate the difference in implementations. Let’s take a look at <a href="http://spinejs.com/">Spine.js</a>:</p>
<p>In this example, we’re going to have a controller called <code>TodoController</code> which would be in charge of individual todos in the application. It will ensure that when the view updates (e.g a user edited the todo) the corresponding model does too.</p>
<p>(Note: We won’t be delving heavily into Spine.js beyond this example, but it’s worth looking at it to learn more about JavaScript frameworks in general.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Controllers in Spine are created by inheriting from Spine.Controller</span>
<span class="kw">var</span> TodoController = <span class="kw">Spine.Controller</span>.<span class="fu">sub</span>({
<span class="dt">init</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="ch">&#39;update&#39;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">render</span>));
<span class="kw">this</span>.<span class="fu">item</span>.<span class="fu">bind</span>(<span class="ch">&#39;destroy&#39;</span>, <span class="kw">this</span>.<span class="fu">proxy</span>(<span class="kw">this</span>.<span class="fu">remove</span>));
},
<span class="dt">render</span>: <span class="kw">function</span>(){
<span class="co">// Handle templating</span>
<span class="kw">this</span>.<span class="fu">replace</span>($(<span class="ch">&#39;#todo-template&#39;</span>).<span class="fu">tmpl</span>(<span class="kw">this</span>.<span class="fu">item</span>));
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="dt">remove</span>: <span class="kw">function</span>(){
<span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">remove</span>();
<span class="kw">this</span>.<span class="fu">release</span>();
}
});</code></pre>
<p>In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller).</p>
<p>What we’re doing in the above example is setting up listeners in the <code>update</code> and <code>destroy</code> events using <code>render()</code> and <code>remove()</code>. When a todo entry gets updated, we re-render the view to reflect the changes to the todo title. Similarly, if the todo gets deleted from todo list, we remove it from the view. In case you were wondering about the <code>tmpl()</code> function in the code snippet: in the <code>render()</code> function, we’re using this to render a JavaScript template called #todoTemplate which simply returns an HTML string used to replace the controller’s current element.</p>
<p>What this provides us with is a very lightweight, simple way to manage changes between the model and the view.</p>
<p><strong>Backbone.js</strong></p>
<p>Later on in this section we’re going to revisit the differences between Backbone and traditional MVC, but for now let’s focus on controllers.</p>
<p>In Backbone, controller logic is shared between Backbone.View and Backbone.Router. Earlier releases of Backbone contained something called Backbone.Controller, but it was renamed to Router to clarify its role.</p>
<p>A Router’s main purpose is to translate URL requests into application states. It does that by mapping URLs to functions. When a user browses to the URL www.example.com/filter/completed, a Router could be used to show just todos which are completed, and to define what application behavior should be run in response to that request. Routers <em>can</em> contain traditional controller responsibilities, such as binding the events between models and views, or rendering parts of the page. However, Backbone contributor Tim Branyen has pointed out that it’s possible to get away without needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="dt">routes</span>: { <span class="st">&quot;/filter/:name&quot;</span>: <span class="st">&quot;setFilter&quot;</span> },
<span class="dt">setFilter</span>: <span class="kw">function</span> (name) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;set filter: &quot;</span> + name); }
});
<span class="kw">var</span> router = <span class="kw">new</span> TodoRouter();
<span class="kw">Backbone.history</span>.<span class="fu">start</span>();</code></pre>
<h2 id="what-does-mvc-give-us"><a href="#TOC">What does MVC give us?</a></h2>
<p>To summarize, the separation of concerns in MVC facilitates modularization of an application’s functionality and enables:</p>
<ul>
<li>Easier overall maintenance. When updates need to be made to the application it is clear whether the changes are data-centric, meaning changes to models and possibly controllers, or merely visual, meaning changes to views.</li>
<li>Decoupling models and views means that it’s straight-forward to write unit tests for business logic</li>
<li>Duplication of low-level model and controller code is eliminated across the application</li>
<li>Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user-interfaces to work simultaneously</li>
</ul>
<h3 id="delving-deeper"><a href="#TOC">Delving deeper</a></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 <q>set of classes to build a user interface</q>. In their view, it’s actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I’ve covered some of these patterns in my other free book, JavaScript Design Patterns For Beginners if you would like to read into them further.</p>
<p>As we’ve discussed, models represent application data, while views handle what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core communication (something that surprisingly isn’t covered in many articles about the MVC pattern). When a model is changed it <q>publishes</q> to the rest of the application that it has been updated. The <q>subscriber</q>–generally a Controller–then updates the view accordingly. The observer-viewer nature of this relationship is what facilitates multiple views being attached to the same model.</p>
<p>For developers interested in knowing more about the decoupled nature of MVC (once again, depending on the implementation), one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different relationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern.</p>
<h3 id="summary"><a href="#TOC">Summary</a></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 grok how the framework expects to be used.</p>
<h2 id="mvp"><a href="#TOC">MVP</a></h2>
<p>Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named <a href="http://en.wikipedia.org/wiki/Taligent">Taligent</a> in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple components, there are some fundamental differences between them.</p>
<p>For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.</p>
<h3 id="models-views-presenters"><a href="#TOC">Models, Views &amp; Presenters</a></h3>
<p>The P in MVP stands for presenter. It’s a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests.</p>
<p>The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes <q>dumb</q>), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other. They effectively bind models to views, a responsibility held by Controllers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views.</p>
<p>Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it’s the presenter’s role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data.</p>
<p>The benefit of this change from MVC is that it increases the testability of your application and provides a more clean separation between the view and the model. This isn’t however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately.</p>
<p>Although a common implementation of a <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a> is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don’t have the interface construct in JavaScript, we’re using it more and more a protocol than an explicit interface here. It’s technically still an API and it’s probably fair for us to refer to it as an interface from that perspective.</p>
<p>There is also a <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a> variation of MVP, which is closer to the MVC and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey’s Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone.</p>
<h2 id="mvp-or-mvc"><a href="#TOC">MVP or MVC?</a></h2>
<p>MVP is generally used most often in enterprise-level applications where it’s necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn’t quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly.</p>
<p>As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application.</p>
<p>Depending on the implementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other components. In my experience this really depends on the languages you are implementing MVP in (there’s quite a difference between opting for MVP for a JavaScript project over one for say, ASP.NET).</p>
<p>At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for.</p>
<h2 id="mvc-mvp-and-backbone.js"><a href="#TOC">MVC, MVP and Backbone.js</a></h2>
<p>There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVP patterns in their classical form as many JavaScript developers don’t view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.NET or GWT). This is because it’s possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC.</p>
<p>Backbone contributor <a href="http://ireneros.com/">Irene Ros</a> subscribes to this way of thinking as when she separates Backbone views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a <code>Backbone.Router</code>, covered later in the book) or a callback in response to data being fetched.</p>
<p>That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that:</p>
<ul>
<li>The presenter in MVP better describes the <code>Backbone.View</code> (the layer between View templates and the data bound to it) than a controller does</li>
<li>The model fits <code>Backbone.Model</code> (it isn’t that different from the classical MVC <q>Model</q>)</li>
<li>The views best represent templates (e.g Handlebars/Mustache markup templates)</li>
</ul>
<p>A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by <code>Backbone.View</code> because they’re able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.</p>
<p>We’ve also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true.</p>
<p>Here, our Backbone <code>TodoView</code> uses the Observer pattern to <q>subscribe</q> to changes to a View’s model in the line <code>this.model.on('change',...)</code>. It also handles templating in the <code>render()</code> method, but unlike some other implementations, user interaction is also handled in the View (see <code>events</code>).</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// The DOM element for a todo item...</span>
<span class="kw">app</span>.<span class="fu">TodoView</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="co">//... is a list tag.</span>
<span class="dt">tagName</span>: <span class="ch">&#39;li&#39;</span>,
<span class="co">// Pass the contents of the todo template through a templating</span>
<span class="co">// function, cache it for a single todo</span>
<span class="dt">template</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#item-template&#39;</span>).<span class="fu">html</span>() ),
<span class="co">// The DOM events specific to an item.</span>
<span class="dt">events</span>: {
<span class="ch">&#39;click .toggle&#39;</span>: <span class="ch">&#39;togglecompleted&#39;</span>
},
<span class="co">// The TodoView listens for changes to its model, re-rendering. Since there&#39;s</span>
<span class="co">// a one-to-one correspondence between a **Todo** and a **TodoView** in this</span>
<span class="co">// app, we set a direct reference on the model for convenience.</span>
<span class="dt">initialize</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;change&#39;</span>, <span class="kw">this</span>.<span class="fu">render</span>, <span class="kw">this</span> );
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">on</span>( <span class="ch">&#39;destroy&#39;</span>, <span class="kw">this</span>.<span class="fu">remove</span>, <span class="kw">this</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="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">template</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="co">// Toggle the `&quot;completed&quot;` state of the model.</span>
<span class="dt">togglecompleted</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toggle</span>();
},
});</code></pre>
<p>Another (quite different) opinion is that Backbone more closely resembles <a href="http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController">Smalltalk-80 MVC</a>, which we went through earlier.</p>
<p>As regular Backbone user Derick Bailey has <a href="http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/">written</a>, it’s ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone doesn’t fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well. Call it <strong>the Backbone way</strong>, MV* or whatever helps reference its flavor of application architecture.</p>
<p>It <em>is</em> however worth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained.</p>
<h2 id="fast-facts"><a href="#TOC">Fast facts</a></h2>
<h3 id="backbone.js"><a href="#TOC">Backbone.js</a></h3>
<ul>
<li>Core components: Model, View, Collection, Router. Enforces its own flavor of MV*</li>
<li>Used by large companies such as SoundCloud and Foursquare to build non-trivial applications</li>
<li>Event-driven communication between views and models. As we’ll see, it’s relatively straight-forward to add event listeners to any attribute in a model, giving developers fine-grained control over what changes in the view</li>
<li>Supports data bindings through manual events or a separate Key-value observing (KVO) library</li>
<li>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. Backbone works well with libraries like Handlebars</li>
<li>Doesn’t support deeply nested models, though there are Backbone plugins such as <a href="https://github.com/PaulUithol/Backbone-relational">Backbone-relational</a> which can help</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>
<h1 id="the-internals"><a href="#TOC">The Internals</a></h1>
<p>In this section, you’ll learn the essentials of Backbone’s models, views, collections and routers, as well as about using namespacing to organize your code. This isn’t meant as a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications with it.</p>
<ul>
<li>Models</li>
<li>Collections</li>
<li>Routers</li>
<li>Views</li>
<li>Dependencies</li>
<li>Namespacing</li>
</ul>
<h2 id="models-1"><a href="#TOC">Models</a></h2>
<p>Backbone models contain interactive data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a 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="kw">Backbone.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> Todo();
<span class="kw">console</span>.<span class="fu">log</span>(todo1);
<span class="co">// or with some arbitrary data:</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">&#39;Check attributes property of the both model instances in the console.&#39;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(todo2);</code></pre>
<h4 id="initialization"><a href="#TOC">Initialization</a></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="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;This model has been initialized.&#39;</span>);
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();</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="kw">Backbone.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="ch">&#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> Todo();
<span class="kw">console</span>.<span class="fu">log</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> Todo({
<span class="dt">title</span>: <span class="ch">&#39;Check attributes property of the logged models in the console.&#39;</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(todo2);
<span class="co">// Or with all of the (default) attributes:</span>
<span class="kw">var</span> todo3 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">&#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="kw">console</span>.<span class="fu">log</span>(todo3);</code></pre>
<h4 id="getters-setters"><a href="#TOC">Getters &amp; Setters</a></h4>
<p><strong>Model.get()</strong></p>
<p><code>Model.get()</code> provides easy access to a model’s attributes. All attributes, regardless if default ones or one passed through to the model on instantiation, are available for retrieval.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.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="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo1</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>)); <span class="co">// empty string</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo1</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>)); <span class="co">// false</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="st">&quot;Retrieved with models get() method.&quot;</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>)); <span class="co">// Retrieved with models get() method.</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">get</span>(<span class="ch">&#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. Despite the name it doesn’t return a JSON string but a copy of the attributes as an object. (<q>toJSON</q> is part of the JSON.stringify specification. Passing an object with a toJSON method makes it stringify the return value of that method instead of the object itself.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.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="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="kw">var</span> todo1Attributes = <span class="kw">todo1</span>.<span class="fu">toJSON</span>();
<span class="co">// Following logs: {&quot;title&quot;:&quot;&quot;,&quot;completed&quot;:false} </span>
<span class="kw">console</span>.<span class="fu">log</span>(todo1Attributes);
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<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 examples and check results in console.&quot;,&quot;completed&quot;:true}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">toJSON</span>());</code></pre>
<p><strong>Model.set()</strong></p>
<p><code>Model.set()</code> allows us to pass attributes into an instance of our model. Attributes can either be set during initialization or at any time afterwards. Backbone uses Model.set() to know when to broadcast that a model’s data has changed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.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="ch">&#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> Todo({
<span class="dt">title</span>: <span class="st">&quot;Set through instantiation.&quot;</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Todo title: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Completed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));
<span class="co">// Set single attribute value at the time through Model.set():</span>
<span class="kw">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="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Todo title: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Completed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));
<span class="co">// Set map of attributes through Model.set():</span>
<span class="kw">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="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Todo title: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Completed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));</code></pre>
<p><strong>Direct access</strong></p>
<p>If you really need to access the attributes in a model’s instance directly, there is <code>Model.attributes</code>. But remember it is best practice to use Model.get(), Model.set() or direct instantiation as explained above.</p>
<h4 id="listening-for-changes-to-your-model"><a href="#TOC">Listening for changes to your model</a></h4>
<p>Any and all of the attributes in a Backbone model can have listeners bound to them which detect when their values change. Listeners can be added to the <code>initialize()</code> function:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.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="ch">&#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="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="ch">&#39;change&#39;</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;- Values for this model have changed.&#39;</span>);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;title&#39;</span>, <span class="ch">&#39;On each change of attribute values listener is triggered.&#39;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Title has changed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;completed&#39;</span>, <span class="kw">true</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Completed has changed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));
<span class="kw">myTodo</span>.<span class="fu">set</span>({
<span class="dt">title</span>: <span class="ch">&#39;Listener is triggered for each change, not for change of the each attribute.&#39;</span>,
<span class="ch">&#39;complete&#39;</span>: <span class="kw">true</span>
});</code></pre>
<p>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="kw">Backbone.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="ch">&#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="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="ch">&#39;change:title&#39;</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Title value for this model have 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> Todo();
<span class="co">// Following changes trigger the listener:</span>
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;title&#39;</span>, <span class="ch">&#39;Check what\&#39;s logged.&#39;</span>);
<span class="kw">myTodo</span>.<span class="fu">setTitle</span>(<span class="ch">&#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="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;completed&#39;</span>, <span class="kw">true</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Todo set as completed: &#39;</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">&#39;completed&#39;</span>));</code></pre>
<h4 id="validation"><a href="#TOC">Validation</a></h4>
<p>Backbone supports model validation through <code>Model.validate()</code>, which allows checking the attribute values for a model prior to them being set.</p>
<p>Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from <code>.validate()</code>. If they are invalid, a custom error can be returned instead.</p>
<p>A basic example for validation can be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">validate</span>: <span class="kw">function</span>(attribs){
<span class="kw">if</span>(<span class="kw">attribs</span>.<span class="fu">title</span> === undefined){
<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="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;This model has been initialized.&#39;</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="st">&quot;error&quot;</span>, <span class="kw">function</span>(model, error){
<span class="kw">console</span>.<span class="fu">log</span>(error);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;completed&#39;</span>, <span class="kw">false</span>); <span class="co">// logs: Remember to set a title for your todo.</span></code></pre>
<p><strong>Note</strong>: Backbone passes the <code>attributes</code> object (attribs param in above example) by shallow copy to the <code>validate</code> function using the Underscore <code>_.extend</code> method. This means that it is not possible to change any Number, String or Boolean attribute but it <em>is</em> possible to change attributes of objects because they are passed by reference. As shallow copy doesn’t copy objects by implicitly copying them, but rather, by reference, one can change the attributes on those objects.</p>
<p>An example of this (by @fivetanley) is available <a href="http://jsfiddle.net/2NdDY/7/">here</a>.</p>
<h2 id="views-1"><a href="#TOC">Views</a></h2>
<p>Views in Backbone don’t contain the markup for your application, but rather they are there to support models by defining the logic for how they should be represented to the user. This is usually achieved using JavaScript templating (e.g. Mustache, jQuery-tmpl, etc.). A view’s <code>render()</code> function can be bound to a model’s <code>change()</code> event, allowing the view to always be up to date without requiring a full page refresh.</p>
<h4 id="creating-new-views"><a href="#TOC">Creating new views</a></h4>
<p>Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend <code>Backbone.View</code>. I’ll explain this code in detail below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="ch">&#39;li&#39;</span>,
<span class="co">// Cache the template function for a single item.</span>
<span class="dt">todoTpl</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">&#39;#item-template&#39;</span>).<span class="fu">html</span>() ),
<span class="dt">events</span>: {
<span class="ch">&#39;dblclick label&#39;</span>: <span class="ch">&#39;edit&#39;</span>,
<span class="ch">&#39;keypress .edit&#39;</span>: <span class="ch">&#39;updateOnEnter&#39;</span>,
<span class="ch">&#39;blur .edit&#39;</span>: <span class="ch">&#39;close&#39;</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="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">todoTpl</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">&#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> TodoView();
<span class="co">// logs reference to a DOM element that cooresponds to the view instance</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todoView</span>.<span class="fu">el</span>);</code></pre>
<h4 id="what-is-el"><a href="#TOC">What is <code>el</code>?</a></h4>
<p><code>el</code> is basically a reference to a DOM element and all views must have one. It allows for all of the contents of a view to be inserted into the DOM at once, which makes for faster rendering because the browser performs the minimum required reflows and repaints.</p>
<p>There are two ways to attach a DOM element to a view: a new element is created for the view and added manually by the developer or the element already exists in the page.</p>
<p>If you want to create a new element for your view, set any combination of the following view’s properties: <code>tagName</code>, <code>id</code> and <code>className</code>. A new element will be created for you by the framework and a reference to it will be available at the <code>el</code> property. If nothing is specified <code>el</code> defaults to <code>div</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="ch">&#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="ch">&#39;container&#39;</span>, <span class="co">// optional, you can assign multiple classes to this property like so &#39;container homepage&#39;</span>
<span class="dt">id</span>: <span class="ch">&#39;todos&#39;</span>, <span class="co">// optional</span>
});
<span class="kw">var</span> todosView = <span class="kw">new</span> TodosView();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todosView</span>.<span class="fu">el</span>);</code></pre>
<p>The above code creates the <code>DOMElement</code> 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"><span class="dt">el</span>: <span class="ch">&#39;#footer&#39;</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.</p>
<p>The <code>_.template</code> method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the above view, I’m passing the markup from a template with id <code>item-template</code> to <code>_.template()</code> to be compiled. Next, I set the html of the <code>el</code> DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.</p>
<p>Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.</p>
<p><strong>The <code>events</code> attribute</strong></p>
<p>The Backbone <code>events</code> attribute allows us to attach event listeners to either custom selectors, or directly to <code>el</code> if no selector is provided. An event takes the form <code>{'eventName selector': 'callbackFunction'}</code> and a number of DOM event-types are supported, including <code>click</code>, <code>submit</code>, <code>mouseover</code>, <code>dblclick</code> and more.</p>
<p>What isn’t instantly obvious is that under the bonnet, Backbone uses jQuery’s <code>.delegate()</code> to provide instant support for event delegation but goes a little further, extending it so that <code>this</code> always refers to the current view object. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.</p>
<h2 id="collections"><a href="#TOC">Collections</a></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 pass through a property specifying the model that your collection will contain, as well as any instance properties required.</p>
<p>In the following example, we create a TodoCollection that will contain our Todo models:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">localStorage</span>: <span class="kw">new</span> Store(<span class="ch">&#39;todos-backbone&#39;</span>)
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo({<span class="dt">title</span>:<span class="ch">&#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> TodosCollection([myTodo]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);
<span class="co">// Collection&#39;s convenience method used to create </span>
<span class="co">// new model instance within collection itself.</span>
<span class="kw">todos</span>.<span class="fu">create</span>({<span class="dt">title</span>:<span class="ch">&#39;Try out code examples&#39;</span>, <span class="dt">id</span>: <span class="dv">48</span>});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);</code></pre>
<p><strong>Getters and Setters</strong></p>
<p>There are a few different ways to retrieve a model from a collection. The most straight-forward is to use <code>Collection.get()</code> which accepts a single id as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// extends on previous example</span>
<span class="kw">var</span> todo2 = <span class="kw">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="kw">console</span>.<span class="fu">log</span>(todo2 === myTodo);</code></pre>
<p>Internally <code>Backbone.Collection</code> sets an array of models enumerated by their <code>id</code> property, if model instances happen to have one. Once <code>collection.get(id)</code> is called this array is checked for existence of the model instance with the corresponding <code>id</code>.</p>
<p>Sometimes you may also want to get a model based on its client id. The client id is a property that Backbone automatically assigns models that have not yet been saved. You can get a model’s client id from its <code>.cid</code> property.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// extends on previous examples</span>
<span class="kw">var</span> todoCid = <span class="kw">todos</span>.<span class="fu">get</span>(<span class="kw">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="kw">console</span>.<span class="fu">log</span>(todoCid === myTodo); </code></pre>
<p>Backbone Collections don’t have setters as such, but do support adding new models via <code>.add()</code> and removing models via <code>.remove()</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">&#39;&#39;</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> TodosCollection = <span class="kw">Backbone.Collection</span>.<span class="fu">extend</span>({
<span class="dt">model</span>: Todo,
<span class="dt">localStorage</span>: <span class="kw">new</span> Store(<span class="ch">&#39;todos-backbone&#39;</span>)
});
<span class="kw">var</span> a = <span class="kw">new</span> Todo({ <span class="dt">title</span>: <span class="ch">&#39;Go to Jamaica.&#39;</span>}),
b = <span class="kw">new</span> Todo({ <span class="dt">title</span>: <span class="ch">&#39;Go to China.&#39;</span>}),
c = <span class="kw">new</span> Todo({ <span class="dt">title</span>: <span class="ch">&#39;Go to Disneyland.&#39;</span>});
<span class="kw">var</span> todos = <span class="kw">new</span> TodosCollection([a,b]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);
<span class="kw">todos</span>.<span class="fu">add</span>(c);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);
<span class="kw">todos</span>.<span class="fu">remove</span>([a,b]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);
<span class="kw">todos</span>.<span class="fu">remove</span>(c);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection size: &quot;</span> + <span class="kw">todos</span>.<span class="fu">length</span>);</code></pre>
<p><strong>Listening for events</strong></p>
<p>As collections represent a group of items, we’re also able to listen for <code>add</code> and <code>remove</code> events for when new models are added or removed from the collection. Here’s an example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;add&quot;</span>, <span class="kw">function</span>(todo) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I should &quot;</span> + <span class="kw">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="kw">todo</span>.<span class="fu">get</span>(<span class="st">&quot;completed&quot;</span>) ? <span class="ch">&#39;Yeah!&#39;</span>: <span class="ch">&#39;Not.&#39;</span> ));
});
<span class="kw">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="ch">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to Disneyland.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);</code></pre>
<p>In addition, we’re able to bind a <code>change</code> event to listen for changes to models in the collection.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;change:title&quot;</span>, <span class="kw">function</span>(model) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Changed my mind where I should go, &quot;</span> + <span class="kw">model</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
});
<span class="kw">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="ch">&#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="kw">TodosCollection</span>.<span class="fu">get</span>(<span class="dv">3</span>);
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">&#39;title&#39;</span>, <span class="ch">&#39;go fishing&#39;</span>);</code></pre>
<p><strong>Fetching models from the server</strong></p>
<p><code>Collections.fetch()</code> retrieves a default set of models from the server in the form of a JSON array. When this data returns, the current collection’s contents will be replaced with the contents of the array.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>;
<span class="kw">TodosCollection</span>.<span class="fu">url</span> = <span class="ch">&#39;/todos&#39;</span>;
<span class="kw">TodosCollection</span>.<span class="fu">fetch</span>();</code></pre>
<p>During configuration, Backbone sets a variable to denote if extended HTTP methods are supported by the server. Another setting controls if the server understands the correct MIME type for JSON:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">emulateHTTP</span> = <span class="kw">false</span>;
<span class="kw">Backbone</span>.<span class="fu">emulateJSON</span> = <span class="kw">false</span>;</code></pre>
<p>The Backbone.sync method that uses these values is actually an integral part of Backbone.js. A jQuery-like ajax method is assumed, so HTTP parameters are organised based on jQuery’s API. Searching through the code for calls to the sync method show it’s used whenever a model is saved, fetched, or deleted (destroyed).</p>
<p>Under the covers, <code>Backbone.sync</code> is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto’s ajax implementations to make these RESTful requests, however this can be overridden as per your needs.</p>
<p>The sync function may be overriden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.</p>
<p>There’s no fancy plugin API for adding a persistence layer – simply override Backbone.sync with the same function signature:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model, options) {
};</code></pre>
<p>The default methodMap is useful for working out what the method argument does:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> methodMap = {
<span class="ch">&#39;create&#39;</span>: <span class="ch">&#39;POST&#39;</span>,
<span class="ch">&#39;update&#39;</span>: <span class="ch">&#39;PUT&#39;</span>,
<span class="ch">&#39;delete&#39;</span>: <span class="ch">&#39;DELETE&#39;</span>,
<span class="ch">&#39;read&#39;</span>: <span class="ch">&#39;GET&#39;</span>
};</code></pre>
<p>In the above example if we wanted to log an event when <code>.sync()</code> was called, we could do this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> id_counter = <span class="dv">1</span>;
<span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;I</span><span class="ch">\&#39;</span><span class="st">ve been passed &quot;</span> + method + <span class="st">&quot; with &quot;</span> + <span class="kw">JSON</span>.<span class="fu">stringify</span>(model));
<span class="kw">if</span>(method === <span class="ch">&#39;create&#39;</span>){ <span class="kw">model</span>.<span class="fu">set</span>(<span class="ch">&#39;id&#39;</span>, id_counter++); }
};</code></pre>
<p><strong>Resetting/Refreshing Collections</strong></p>
<p>Rather than adding or removing models individually, you might occasionally wish to update an entire collection at once. <code>Collection.reset()</code> allows us to replace an entire collection with new models as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;reset&quot;</span>, <span class="kw">function</span>() {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection reseted.&quot;</span>);
});
<span class="kw">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="ch">&#39;go to Jamaica.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to Disneyland.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Collection size: &#39;</span> + <span class="kw">TodosCollection</span>.<span class="fu">length</span>);
<span class="kw">TodosCollection</span>.<span class="fu">reset</span>([
{ <span class="dt">title</span>: <span class="ch">&#39;go to Cuba.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> }
]);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Collection size: &#39;</span> + <span class="kw">TodosCollection</span>.<span class="fu">length</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 example.</p>
<h3 id="underscore-utility-functions"><a href="#TOC">Underscore utility functions</a></h3>
<p>As Backbone requires Underscore as a hard dependency, we’re able to use many of the utilities it has to offer to aid with our application development. Here’s an example of how Underscore’s <code>forEach</code> method that can be used for iterating over collection and <code>sortBy()</code> method that can be used to sort a collection of todos based on a particular attribute.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosCollection = <span class="kw">new</span> <span class="kw">Backbone</span>.<span class="fu">Collection</span>();
<span class="kw">TodosCollection</span>.<span class="fu">on</span>(<span class="st">&quot;reset&quot;</span>, <span class="kw">function</span>() {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Collection reseted.&quot;</span>);
});
<span class="kw">TodosCollection</span>.<span class="fu">add</span>([
{ <span class="dt">title</span>: <span class="ch">&#39;go to Belgium.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to China.&#39;</span>, <span class="dt">completed</span>: <span class="kw">false</span> },
{ <span class="dt">title</span>: <span class="ch">&#39;go to Austria.&#39;</span>, <span class="dt">completed</span>: <span class="kw">true</span> }
]);
<span class="kw">TodosCollection</span>.<span class="fu">forEach</span>(<span class="kw">function</span>(model){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">model</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
});
<span class="kw">var</span> sortedByAlphabet = <span class="kw">TodosCollection</span>.<span class="fu">sortBy</span>(<span class="kw">function</span> (todo) {
<span class="kw">return</span> <span class="kw">todo</span>.<span class="fu">get</span>(<span class="st">&quot;title&quot;</span>).<span class="fu">toLowerCase</span>();
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;- Now sorted: &quot;</span>);
<span class="kw">sortedByAlphabet</span>.<span class="fu">forEach</span>(<span class="kw">function</span>(model){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">model</span>.<span class="fu">get</span>(<span class="ch">&#39;title&#39;</span>));
});</code></pre>
<p>The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official <a href="http://documentcloud.github.com/underscore/">docs</a>.</p>
<h3 id="chainable-api"><a href="#TOC">Chainable API</a></h3>
<p>Speaking of utility methods, another bit of sugar in Backbone is the support for Underscore’s chain method. This works by calling the original method with the current array of models and returning the result. 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="kw">Backbone</span>.<span class="fu">Collection</span>([
{ <span class="dt">name</span>: <span class="ch">&#39;Tim&#39;</span>, <span class="dt">age</span>: <span class="dv">5</span> },
{ <span class="dt">name</span>: <span class="ch">&#39;Ida&#39;</span>, <span class="dt">age</span>: <span class="dv">26</span> },
{ <span class="dt">name</span>: <span class="ch">&#39;Rob&#39;</span>, <span class="dt">age</span>: <span class="dv">55</span> }
]);
<span class="kw">var</span> filteredNames = <span class="kw">collection</span>.<span class="fu">chain</span>()
.<span class="fu">filter</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="kw">item</span>.<span class="fu">get</span>(<span class="ch">&#39;age&#39;</span>) &gt; <span class="dv">10</span>; })
.<span class="fu">map</span>(<span class="kw">function</span>(item) { <span class="kw">return</span> <span class="kw">item</span>.<span class="fu">get</span>(<span class="ch">&#39;name&#39;</span>); })
.<span class="fu">value</span>();
<span class="kw">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 will return this, 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="kw">Backbone</span>.<span class="fu">Collection</span>();
collection
.<span class="fu">add</span>({ <span class="dt">name</span>: <span class="ch">&#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="ch">&#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="ch">&#39;Steve&#39;</span>, <span class="dt">age</span>: <span class="dv">41</span> });
<span class="kw">var</span> names = <span class="kw">collection</span>.<span class="fu">pluck</span>(<span class="ch">&#39;name&#39;</span>);
<span class="kw">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="events"><a href="#TOC">Events</a></h2>
<p>As we’ve covered, <code>Backbone.Events</code> is mixed into the other Backbone <q>classes</q>, including:</p>
<ul>
<li>Backbone.Model</li>
<li>Backbone.Collection</li>
<li>Backbone.Router</li>
<li>Backbone.History</li>
<li>Backbone.View</li>
</ul>
<p>Events are the standard way to deal with user interface actions, through the declarative event bindings on views, and also model and collection changes. Mastering events is one of the quickest ways to become more productive with Backbone.</p>
<p><code>Backbone.Events</code> also has the ability to give any object a way to bind and trigger custom events. We can mix this module into any object easily and there isn’t a requirement for events to be declared prior to them being bound.</p>
<p>Example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="co">// Add a custom event</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="ch">&#39;dance&#39;</span>, <span class="kw">function</span>(msg){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;We triggered &#39;</span> + msg);
});
<span class="co">// Trigger the custom event</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="ch">&#39;dance&#39;</span>, <span class="ch">&#39;our event&#39;</span>);</code></pre>
<p>If you’re familiar with jQuery custom events or the concept of Publish/Subscribe, <code>Backbone.Events</code> provides a system that is very similar with <code>on</code> being analogous to <code>subscribe</code> and <code>trigger</code> being similar to <code>publish</code>.</p>
<p><code>on</code> basically allows us to bind a callback function to any object, as we’ve done with <code>dance</code> in the above example. Whenever the event is fired, our callback is invoked.</p>
<p>The official Backbone.js documentation recommends namespacing event names using colons if you end up using quite a few of these on your page. e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> dancing (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We started &quot;</span> + msg); }
<span class="co">// Add a namespaced custom events</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance:tap&quot;</span>, dancing);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance:break&quot;</span>, dancing);
<span class="co">// Trigger the custom events.</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:tap&quot;</span>, <span class="st">&quot;tap dancing. Yeah!&quot;</span>);
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:break&quot;</span>, <span class="st">&quot;break dancing. Yeah!&quot;</span>);
<span class="co">// This one triggers nothing as no listener listens for it</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, <span class="st">&quot;break dancing. Yeah!&quot;</span>);</code></pre>
<p>A special <code>all</code> event is made available in case you would like an event to be triggered when any event occurs (e.g if you would like to screen events in a single location). The <code>all</code> event can be used as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> dancing (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We started &quot;</span> + msg); }
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;all&quot;</span>, <span class="kw">function</span>(eventName){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;The name of the event passed was &quot;</span> + eventName);
});
<span class="co">// This time each event will be catched with catch &#39;all&#39; event listener</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:tap&quot;</span>, <span class="st">&quot;tap dancing. Yeah!&quot;</span>);
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:break&quot;</span>, <span class="st">&quot;break dancing. Yeah!&quot;</span>);
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, <span class="st">&quot;break dancing. Yeah!&quot;</span>);</code></pre>
<p><code>off</code> allows us to remove a callback function that has previously been bound from an object. Going back to our Publish/Subscribe comparison, think of it as an <code>unsubscribe</code> for custom events.</p>
<p>To remove the <code>dance</code> event we previously bound to <code>ourObject</code>, we would simply do:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> dancing (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We &quot;</span> + msg); }
<span class="co">// Add a namespaced custom events</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance:tap&quot;</span>, dancing);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance:break&quot;</span>, dancing);
<span class="co">// Trigger the custom events. Each will be catched and acted upon.</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:tap&quot;</span>, <span class="st">&quot;started tap dancing. Yeah!&quot;</span>);
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:break&quot;</span>, <span class="st">&quot;started break dancing. Yeah!&quot;</span>);
<span class="co">// Removes event bound to the object</span>
<span class="kw">ourObject</span>.<span class="fu">off</span>(<span class="st">&quot;dance:tap&quot;</span>);
<span class="co">// Trigger the custom events again, but one is logged.</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:tap&quot;</span>, <span class="st">&quot;stopped tap dancing.&quot;</span>); <span class="co">// won&#39;t be logged as its not listened for</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance:break&quot;</span>, <span class="st">&quot;break dancing. Yeah!&quot;</span>);</code></pre>
<p>To remove all callbacks for the event we should just pass event name (e.g <code>move</code>) to <code>off()</code> function of the object event is bound to. If we wish to remove just a callback by a specific name, we can pass callback name as second parameter:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> dancing (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We are dancing. &quot;</span> + msg); }
<span class="kw">function</span> jumping (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We are jumping. &quot;</span> + msg); }
<span class="co">// Add two listeners to the same event</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;move&quot;</span>, dancing);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;move&quot;</span>, jumping);
<span class="co">// Trigger the events. Both listeners are called.</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;move&quot;</span>, <span class="st">&quot;Yeah!&quot;</span>);
<span class="co">// Removes specified listener</span>
<span class="kw">ourObject</span>.<span class="fu">off</span>(<span class="st">&quot;move&quot;</span>, dancing);
<span class="co">// Trigger the events again. One listener left.</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;move&quot;</span>, <span class="st">&quot;Yeah, jump, jump!&quot;</span>);</code></pre>
<p>Finally, <code>trigger</code> triggers a callback for a specified event (or a space-separated list of events). e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> doAction (msg) { <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We are &quot;</span> + msg); }
<span class="co">// Add event listeners</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance&quot;</span>, doAction);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;jump&quot;</span>, doAction);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;skip&quot;</span>, doAction);
<span class="co">// Single event</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, <span class="ch">&#39;just dancing.&#39;</span>);
<span class="co">// Multiple events</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance jump skip&quot;</span>, <span class="ch">&#39;very tired from so much action.&#39;</span>);</code></pre>
<p>It is also possible to pass along additional arguments to each (or all) of these events via a second argument supported by <code>trigger</code>. e.g:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> ourObject = {};
<span class="co">// Mixin</span>
<span class="kw">_</span>.<span class="fu">extend</span>(ourObject, <span class="kw">Backbone</span>.<span class="fu">Events</span>);
<span class="kw">function</span> doAction (actionObj) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;We are &quot;</span> + <span class="kw">actionObj</span>.<span class="fu">action</span> + <span class="ch">&#39; for &#39;</span> + <span class="kw">actionObj</span>.<span class="fu">duration</span> );
}
<span class="co">// Add event listeners</span>
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;dance&quot;</span>, doAction);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;jump&quot;</span>, doAction);
<span class="kw">ourObject</span>.<span class="fu">on</span>(<span class="st">&quot;skip&quot;</span>, doAction);
<span class="co">// Passing multiple arguments to single event</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance&quot;</span>, {<span class="dt">duration</span>: <span class="st">&quot;5 minutes&quot;</span>, <span class="dt">action</span>: <span class="ch">&#39;dancing&#39;</span>});
<span class="co">// Passing multiple arguments to multiple events</span>
<span class="kw">ourObject</span>.<span class="fu">trigger</span>(<span class="st">&quot;dance jump skip&quot;</span>, {<span class="dt">duration</span>: <span class="st">&quot;15 minutes&quot;</span>, <span class="dt">action</span>: <span class="ch">&#39;on fire&#39;</span>});</code></pre>
<h2 id="routers"><a href="#TOC">Routers</a></h2>
<p>In Backbone, routers are used to help manage application state and for connecting URLs to application events. This is achieved using hash-tags with URL fragments, or using the browser’s pushState and History API. Some examples of routes may be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">http</span>:<span class="co">//example.com/#about</span>
<span class="dt">http</span>:<span class="co">//example.com/#search/seasonal-horns/page2</span></code></pre>
<p>Note: An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that particular route. This relationship is defined as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="ch">&#39;route&#39;</span> : <span class="ch">&#39;mappedFunction&#39;</span></code></pre>
<p>Let us now define our first controller by extending <code>Backbone.Router</code>. For the purposes of this guide, we’re going to continue pretending we’re creating a complex todo application (something like personal organize/planner) that requires a complex TodoRouter.</p>
<p>Note the inline comments in the code example below as they continue the rest of the lesson on routers.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="co">/* define the route and function maps for this router */</span>
<span class="dt">routes</span>: {
<span class="st">&quot;about&quot;</span> : <span class="st">&quot;showAbout&quot;</span>,
<span class="co">/* Sample usage: http://example.com/#about */</span>
<span class="st">&quot;todo/:id&quot;</span> : <span class="st">&quot;getTodo&quot;</span>,
<span class="co">/* This is an example of using a &quot;:param&quot; variable which allows us to match</span>
<span class="co"> any of the components between two URL slashes */</span>
<span class="co">/* Sample usage: http://example.com/#todo/5 */</span>
<span class="st">&quot;search/:query&quot;</span> : <span class="st">&quot;searchTodos&quot;</span>,
<span class="co">/* We can also define multiple routes that are bound to the same map function,</span>
<span class="co"> in this case searchTodos(). Note below how we&#39;re optionally passing in a</span>
<span class="co"> reference to a page number if one is supplied */</span>
<span class="co">/* Sample usage: http://example.com/#search/job */</span>
<span class="st">&quot;search/:query/p:page&quot;</span> : <span class="st">&quot;searchTodos&quot;</span>,
<span class="co">/* As we can see, URLs may contain as many &quot;:param&quot;s as we wish */</span>
<span class="co">/* Sample usage: http://example.com/#search/job/p1 */</span>
<span class="st">&quot;todos/:id/download/*documentPath&quot;</span> : <span class="st">&quot;downloadDocument&quot;</span>,
<span class="co">/* This is an example of using a *splat. splats are able to match any number of</span>
<span class="co"> URL components and can be combined with &quot;:param&quot;s*/</span>
<span class="co">/* Sample usage: http://example.com/#todos/5/download/files/Meeting_schedule.doc */</span>
<span class="co">/* If you wish to use splats for anything beyond default routing, it&#39;s probably a good</span>
<span class="co"> idea to leave them at the end of a URL otherwise you may need to apply regular</span>
<span class="co"> expression parsing on your fragment */</span>
<span class="st">&quot;*other&quot;</span> : <span class="st">&quot;defaultRoute&quot;</span>
<span class="co">/* This is a default route that also uses a *splat. Consider the</span>
<span class="co"> default route a wildcard for URLs that are either not matched or where</span>
<span class="co"> the user has incorrectly typed in a route path manually */</span>
<span class="co">/* Sample usage: http://example.com/# &lt;anything */</span>
},
<span class="dt">showAbout</span>: <span class="kw">function</span>(){
},
<span class="dt">getTodo</span>: <span class="kw">function</span>(id){
<span class="co">/*</span>
<span class="co"> Note that the id matched in the above route will be passed to this function</span>
<span class="co"> */</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;You are trying to reach todo &quot;</span> + id);
},
<span class="dt">searchTodos</span>: <span class="kw">function</span>(query, page){
<span class="kw">var</span> page_number = page || <span class="dv">1</span>;
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Page number: &quot;</span> + page_number + <span class="st">&quot; of the results for todos containing the word: &quot;</span> + query);
},
<span class="dt">downloadDocument</span>: <span class="kw">function</span>(id, path){
},
<span class="dt">defaultRoute</span>: <span class="kw">function</span>(other){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Invalid. You attempted to reach:&#39;</span> + other);
}
});
<span class="co">/* Now that we have a router setup, remember to instantiate it */</span>
<span class="kw">var</span> myTodoRouter = <span class="kw">new</span> TodoRouter();</code></pre>
<p>As of Backbone 0.5+, it’s possible to opt-in for HTML5 pushState support via <code>window.history.pushState</code>. This permits you to define routes such as http://www.scriptjunkie.com/just/an/example. This will be supported with automatic degradation when a user’s browser doesn’t support pushState. For the purposes of this tutorial, we’ll use the hashtag method.</p>
<h4 id="is-there-a-limit-to-the-number-of-routers-i-should-be-using"><a href="#TOC">Is there a limit to the number of routers I should be using?</a></h4>
<p>Andrew de Andrade has pointed out that DocumentCloud themselves usually only use a single router in most of their applications. You’re very likely to not require more than one or two routers in your own projects as the majority of your application routing can be kept organized in a single controller without it getting unwieldy.</p>
<h4 id="backbone.history"><a href="#TOC">Backbone.history</a></h4>
<p>Next, we need to initialize <code>Backbone.history</code> as it handles <code>hashchange</code> events in our application. This will automatically handle routes that have been defined and trigger callbacks when they’ve been accessed.</p>
<p>The <code>Backbone.history.start()</code> method will simply tell Backbone that it’s OK to begin monitoring all <code>hashchange</code> events as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="co">/* define the route and function maps for this router */</span>
<span class="dt">routes</span>: {
<span class="st">&quot;about&quot;</span> : <span class="st">&quot;showAbout&quot;</span>,
<span class="st">&quot;search/:query&quot;</span> : <span class="st">&quot;searchTodos&quot;</span>,
<span class="st">&quot;search/:query/p:page&quot;</span> : <span class="st">&quot;searchTodos&quot;</span>
},
<span class="dt">showAbout</span>: <span class="kw">function</span>(){},
<span class="dt">searchTodos</span>: <span class="kw">function</span>(query, page){
<span class="kw">var</span> page_number = page || <span class="dv">1</span>;
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Page number: &quot;</span> + page_number + <span class="st">&quot; of the results for todos containing the word: &quot;</span> + query);
}
});
<span class="kw">var</span> myTodoRouter = <span class="kw">new</span> TodoRouter();
<span class="kw">Backbone.history</span>.<span class="fu">start</span>();
<span class="co">// Go to and check console:</span>
<span class="co">// http://localhost/#search/job/p3 logs: Page number: 3 of the results for todos containing the word: job</span>
<span class="co">// http://localhost/#search/job logs: Page number: 1 of the results for todos containing the word: job </span>
<span class="co">// etc.</span></code></pre>
<p>Note: To test last example you should set site for testing in local development environment which is out of scope of this book.</p>
<p>As an aside, if you would like to save application state to the URL at a particular point you can use the <code>.navigate()</code> method to achieve this. It simply updates your URL fragment without the need to trigger the <code>hashchange</code> event:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/* Lets imagine we would like a specific fragment (edit) once a user opens single todo */</span>
<span class="kw">var</span> TodoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="dt">routes</span>: {
<span class="st">&quot;todo/:id&quot;</span>: <span class="st">&quot;viewTodo&quot;</span>,
<span class="st">&quot;todo/:id/edit&quot;</span>: <span class="st">&quot;editTodo&quot;</span>
<span class="co">// ... other routes</span>
},
<span class="dt">viewTodo</span>: <span class="kw">function</span>(id){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;View todo requested.&quot;</span>);
<span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;todo/&quot;</span> + id + <span class="ch">&#39;/edit&#39;</span>); <span class="co">// updates the fragment for us, but doesn&#39;t trigger the route</span>
},
<span class="dt">editTodo</span>: <span class="kw">function</span>(id) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Edit todo openned.&quot;</span>);
}
});
<span class="kw">var</span> myTodoRouter = <span class="kw">new</span> TodoRouter();
<span class="kw">Backbone.history</span>.<span class="fu">start</span>();
<span class="co">// Go to:</span>
<span class="co">// http://localhost/#todo/4 url is updated to: http://localhost/#todo/45/edit</span>
<span class="co">// but editTodo() function is not invoked even though location we end up is mapped to it.</span>
<span class="co">//</span>
<span class="co">// logs: View todo requested.</span></code></pre>
<p>It is also possible for <code>Router.navigate()</code> to trigger the route as well as update the URL fragment.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoRouter = <span class="kw">Backbone.Router</span>.<span class="fu">extend</span>({
<span class="dt">routes</span>: {
<span class="st">&quot;todo/:id&quot;</span>: <span class="st">&quot;viewTodo&quot;</span>,
<span class="st">&quot;todo/:id/edit&quot;</span>: <span class="st">&quot;editTodo&quot;</span>
<span class="co">// ... other routes</span>
},
<span class="dt">viewTodo</span>: <span class="kw">function</span>(id){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;View todo requested.&quot;</span>);
<span class="kw">this</span>.<span class="fu">navigate</span>(<span class="st">&quot;todo/&quot;</span> + id + <span class="ch">&#39;/edit&#39;</span>, <span class="kw">true</span>); <span class="co">// updates the fragment and triggers the route as well</span>
},
<span class="dt">editTodo</span>: <span class="kw">function</span>(id) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Edit todo openned.&quot;</span>);
}
});
<span class="kw">var</span> myTodoRouter = <span class="kw">new</span> TodoRouter();
<span class="kw">Backbone.history</span>.<span class="fu">start</span>();
<span class="co">// Go to:</span>
<span class="co">// http://localhost/#todo/4 url is updated to: http://localhost/#todo/45/edit</span>
<span class="co">// but this time editTodo() function is invoked.</span>
<span class="co">// </span>
<span class="co">// logs: </span>
<span class="co">// View todo requested.</span>
<span class="co">// Edit todo openned. </span></code></pre>
<h3 id="backbones-sync-api"><a href="#TOC">Backbone’s Sync API</a></h3>
<p>The Backbone.sync method is intended to be overridden to support other backends. The built-in method is tailored to a certain breed of RESTful JSON APIs – Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT the same way.</p>
<p>The way this works is the model and collection classes have a sync method that calls Backbone.sync. Both will call this.sync internally when fetching, saving, or deleting items.</p>
<p>The sync method is called with three parameters:</p>
<ul>
<li>method: One of create, update, delete, read</li>
<li>model: The Backbone model object</li>
<li>options: May include success and error methods</li>
</ul>
<p>Implementing a new sync method can use the following pattern:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Backbone</span>.<span class="fu">sync</span> = <span class="kw">function</span>(method, model, options) {
<span class="kw">var</span> requestContent = {}, success, error;
<span class="kw">function</span> success(result) {
<span class="co">// Handle results from MyAPI</span>
<span class="kw">if</span> (<span class="kw">options</span>.<span class="fu">success</span>) {
<span class="kw">options</span>.<span class="fu">success</span>(result);
}
}
<span class="kw">function</span> error(result) {
<span class="co">// Handle results from MyAPI</span>
<span class="kw">if</span> (<span class="kw">options</span>.<span class="fu">error</span>) {
<span class="kw">options</span>.<span class="fu">error</span>(result);
}
}
options || (options = {});
<span class="kw">switch</span> (method) {
<span class="kw">case</span> <span class="ch">&#39;create&#39;</span>:
requestContent[<span class="ch">&#39;resource&#39;</span>] = <span class="kw">model</span>.<span class="fu">toJSON</span>();
<span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">create</span>(model, success, error);
<span class="kw">case</span> <span class="ch">&#39;update&#39;</span>:
requestContent[<span class="ch">&#39;resource&#39;</span>] = <span class="kw">model</span>.<span class="fu">toJSON</span>();
<span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">update</span>(model, success, error);
<span class="kw">case</span> <span class="ch">&#39;delete&#39;</span>:
<span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">destroy</span>(model, success, error);
<span class="kw">case</span> <span class="ch">&#39;read&#39;</span>:
<span class="kw">if</span> (<span class="kw">model</span>.<span class="fu">attributes</span>[<span class="kw">model</span>.<span class="fu">idAttribute</span>]) {
<span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">find</span>(model, success, error);
} <span class="kw">else</span> {
<span class="kw">return</span> <span class="kw">MyAPI</span>.<span class="fu">findAll</span>(model, success, error);
}
}
};</code></pre>
<p>This pattern delegates API calls to a new object, which could be a Backbone-style class that supports events. This can be safely tested separately, and potentially used with libraries other than Backbone.</p>
<p>There are quite a few sync implementations out there:</p>
<ul>
<li>Backbone localStorage</li>
<li>Backbone offline</li>
<li>Backbone Redis</li>
<li>backbone-parse</li>
<li>backbone-websql</li>
<li>Backbone Caching Sync</li>
</ul>
<h3 id="conflict-management"><a href="#TOC">Conflict Management</a></h3>
<p>Like most client-side projects, Backbone.js wraps everything in an immediately-invoked function expression:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">(<span class="kw">function</span>(){
<span class="co">// Backbone.js</span>
}).<span class="fu">call</span>(<span class="kw">this</span>);</code></pre>
<p>Several things happen during this configuration stage. A Backbone <q>namespace</q> is created, and multiple versions of Backbone on the same page are supported through the noConflict mode:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> root = <span class="kw">this</span>;
<span class="kw">var</span> previousBackbone = <span class="kw">root</span>.<span class="fu">Backbone</span>;
<span class="kw">Backbone</span>.<span class="fu">noConflict</span> = <span class="kw">function</span>() {
<span class="kw">root</span>.<span class="fu">Backbone</span> = previousBackbone;
<span class="kw">return</span> <span class="kw">this</span>;
};</code></pre>
<p>Multiple versions of Backbone can be used on the same page by calling noConflict like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Backbone19 = <span class="kw">Backbone</span>.<span class="fu">noConflict</span>();
<span class="co">// Backbone19 refers to the most recently loaded version,</span>
<span class="co">// and `window.Backbone` will be restored to the previously</span>
<span class="co">// loaded version</span></code></pre>
<p>This initial configuration code also supports CommonJS modules so Backbone can be used in Node projects:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Backbone;
<span class="kw">if</span> (<span class="kw">typeof</span> exports !== <span class="ch">&#39;undefined&#39;</span>) {
Backbone = exports;
} <span class="kw">else</span> {
Backbone = <span class="kw">root</span>.<span class="fu">Backbone</span> = {};
}</code></pre>
<h2 id="inheritance-mixins"><a href="#TOC">Inheritance &amp; Mixins</a></h2>
<p>For its inheritance, Backbone internally uses an <code>inherits</code> function inspired by <code>goog.inherits</code>, Google’s implementation from the Closure Library. It’s basically a function to correctly setup the prototype chain.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> inherits = <span class="kw">function</span>(parent, protoProps, staticProps) {
...</code></pre>
<p>The only major difference here is that Backbone’s API accepts two objects containing <q>instance</q> and <q>static</q> methods.</p>
<p>Following on from this, for inheritance purposes all of Backbone’s objects contain an <code>extend</code> method as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">Model</span>.<span class="fu">extend</span> = <span class="kw">Collection</span>.<span class="fu">extend</span> = <span class="kw">Router</span>.<span class="fu">extend</span> = <span class="kw">View</span>.<span class="fu">extend</span> = extend;</code></pre>
<p>Most development with Backbone is based around inheriting from these objects, and they’re designed to mimic a classical object-oriented implementation.</p>
<p>If this sounds familiar, it’s because <code>extend</code> is an Underscore.js utility, although Backbone itself does a lot more with this. See below for Underscore’s <code>extend</code>:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">each(<span class="kw">slice</span>.<span class="fu">call</span>(arguments, <span class="dv">1</span>), <span class="kw">function</span>(source) {
<span class="kw">for</span> (<span class="kw">var</span> prop <span class="kw">in</span> source) {
obj[prop] = source[prop];
}
});
<span class="kw">return</span> obj;</code></pre>
<p>The above isn’t quite the same as ES5’s <code>Object.create</code>, as it’s actually copying properties (methods and values) from one object to another. As this isn’t enough to support Backbone’s inheritance and class model, the following steps are performed:</p>
<ul>
<li>The instance methods are checked to see if there’s a constructor property. If so, the class’s constructor is used, otherwise the parent’s constructor is used (i.e., Backbone.Model)</li>
<li>Underscore’s extend method is called to add the parent class’s methods to the new child class</li>
<li>The <code>prototype</code> property of a blank constructor function is assigned with the parent’s prototype, and a new instance of this is set to the child’s <code>prototype</code> property Underscore’s extend method is called twice to add the static and instance methods to the child class</li>
<li>The child’s prototype’s constructor and a <code>__super__</code> property are assigned</li>
<li>This pattern is also used for classes in CoffeeScript, so Backbone classes are compatible with CoffeeScript classes.</li>
</ul>
<p><code>extend</code> can be used for a great deal more and developers who are fans of mixins will like that it can be used for this too. You can define functionality on any custom object, and then quite literally copy &amp; paste all of the methods and attributes from that object to a Backbone one:</p>
<p>For example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"> <span class="kw">var</span> MyMixin = {
<span class="dt">foo</span>: <span class="ch">&#39;bar&#39;</span>,
<span class="dt">sayFoo</span>: <span class="kw">function</span>(){alert(<span class="kw">this</span>.<span class="fu">foo</span>);}
}
<span class="kw">var</span> MyView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="co">// ...</span>
});
<span class="kw">_</span>.<span class="fu">extend</span>(<span class="kw">MyView</span>.<span class="fu">prototype</span>, MyMixin);
myView = <span class="kw">new</span> MyView();
<span class="kw">myView</span>.<span class="fu">sayFoo</span>(); <span class="co">//=&gt; &#39;bar&#39;</span></code></pre>
<p>We can take this further and also apply it to View inheritance. The following is an example of how to extend one View using another:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
});
<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({
});</code></pre>
<p>However, if you have an <code>initialize()</code> method in Panel, then it won’t be called if you also have an <code>initialize()</code> method in PanelAdvanced, so you would have to call Panel’s initialize method explicitly:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(options){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Panel initialized&#39;</span>);
<span class="kw">this</span>.<span class="fu">foo</span> = <span class="ch">&#39;bar&#39;</span>;
}
});
<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(options){
<span class="kw">Panel.prototype.initialize</span>.<span class="fu">call</span>(<span class="kw">this</span>, [options])
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;PanelAdvanced initialized&#39;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">this</span>.<span class="fu">foo</span>); <span class="co">// Log: bar</span>
}
});
<span class="co">// We can also inherit PanelAdvaned if needed</span>
<span class="kw">var</span> PanelAdvancedExtra = <span class="kw">PanelAdvanced</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(options){
<span class="kw">PanelAdvanced.prototype.initialize</span>.<span class="fu">call</span>(<span class="kw">this</span>, [options])
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;PanelAdvancedExtra initialized&#39;</span>);
}
});
<span class="kw">new</span> Panel();
<span class="kw">new</span> PanelAdvanced();
<span class="kw">new</span> PanelAdvancedExtra();</code></pre>
<p>This isn’t the most elegant of solutions because if you have a lot of Views that inherit from Panel, then you’ll have to remember to call Panel’s initialize from all of them.</p>
<p>It’s worth noting that if Panel doesn’t have an initialize method now but you choose to add it in the future, then you’ll need to go to all of the inherited classes in the future and make sure they call Panel’s initialize.</p>
<p>So here’s an alternative way to define Panel so that your inherited views don’t need to call Panel’s initialize method:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Panel = <span class="kw">function</span> (options) {
<span class="co">// put all of Panel&#39;s initialization code here</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;Panel initialized&#39;</span>);
<span class="kw">this</span>.<span class="fu">foo</span> = <span class="ch">&#39;bar&#39;</span>;
<span class="kw">Backbone.View</span>.<span class="fu">apply</span>(<span class="kw">this</span>, [options]);
};
<span class="kw">_</span>.<span class="fu">extend</span>(<span class="kw">Panel</span>.<span class="fu">prototype</span>, <span class="kw">Backbone.View</span>.<span class="fu">prototype</span>, {
<span class="co">// put all of Panel&#39;s methods here. For example:</span>
<span class="dt">sayHi</span>: <span class="kw">function</span> () {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;hello from Panel&#39;</span>);
}
});
<span class="kw">Panel</span>.<span class="fu">extend</span> = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>;
<span class="co">// other classes then inherit from Panel like this:</span>
<span class="kw">var</span> PanelAdvanced = <span class="kw">Panel</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span> (options) {
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">&#39;PanelAdvanced initialized&#39;</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">this</span>.<span class="fu">foo</span>);
}
});
<span class="kw">var</span> PanelAdvanced = <span class="kw">new</span> PanelAdvanced(); <span class="co">//Logs: Panel initialized, PanelAdvanced initialized, bar</span>
<span class="kw">PanelAdvanced</span>.<span class="fu">sayHi</span>(); <span class="co">// Logs: hello from Panel</span></code></pre>
<p>When used appropriately, Underscore’s <code>extend</code> method can save a great deal of time and effort writing redundant code.</p>
<p>(Thanks to <a href="http://dailyjs.com">Alex Young</a>, <a href="http://stackoverflow.com/users/93448/derick-bailey">Derick Bailey</a> and <a href="http://stackoverflow.com/users/188740/johnnyo">JohnnyO</a> for the heads up about these tips).</p>
<h4 id="backbone-super"><a href="#TOC">Backbone-Super</a></h4>
<p><a href="https://github.com/lukasolson/Backbone-Super">Backbone-Super</a> by Lukas Olson adds a <em>_super</em> method to <em>Backbone.Model</em> using <a href="http://ejohn.org/blog/simple-javascript-inheritance/">John Resig’s Inheritance script</a>. Rather than using Backbone.Model.prototype.set.call as per the Backbone.js documentation, _super can be called instead:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// This is how we normally do it</span>
<span class="kw">var</span> OldFashionedNote = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">set</span>: <span class="kw">function</span>( attributes, options ) {
<span class="co">// Call parent&#39;s method</span>
<span class="kw">Backbone.Model.prototype.set</span>.<span class="fu">call</span>(<span class="kw">this</span>, attributes, options);
<span class="co">// some custom code here</span>
<span class="co">// ...</span>
}
});</code></pre>
<p>After including this plugin, you can do the same thing with the following syntax:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// This is how we can do it after using the Backbone-super plugin</span>
<span class="kw">var</span> Note = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">set</span>: <span class="kw">function</span>(attributes, options) {
<span class="co">// Call parent&#39;s method</span>
<span class="kw">this</span>._<span class="fu">super</span>(attributes, options);
<span class="co">// some custom code here</span>
<span class="co">// ...</span>
}
});</code></pre>
<h2 id="dependencies"><a href="#TOC">Dependencies</a></h2>
<p>The official Backbone.js <a href="http://backbonejs.org/">documentation</a> states:</p>
<blockquote>
<p>Backbone’s only hard dependency is Underscore.js ( &gt; 1.3.1). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( &gt; 1.4.2) or Zepto.</p>
</blockquote>
<p><em><a href="https://github.com/bestiejs/lodash">Lo-dash</a>, a fork of Underscore containing performance enhancements is also compatible with Backbone.</em></p>
<p>What this translates to is that if you require working with anything beyond models, you will need to include a DOM manipulation library such as jQuery or Zepto. Underscore is primarily used for it’s utility methods (which Backbone relies upon heaviy) and json2.js for legacy browser JSON support if Backbone.sync is used.</p>
<h3 id="dom-manipulation"><a href="#TOC">DOM Manipulation</a></h3>
<p>Although most developers won’t need it, Backbone does support setting a custom DOM library to be used instead of these options. From the source:</p>
<pre><code>// Set the JavaScript library that will be used for DOM manipulation and
// Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery,
// Zepto, or Ender; but the `setDomLibrary()` method lets you inject an
// alternate JavaScript library (or a mock library for testing your views
// outside of a browser).
Backbone.setDomLibrary = function(lib) {
$ = lib;
};</code></pre>
<p>Calling this method will allow you to use any custom DOM-manipulation library. e.g:</p>
<pre><code>Backbone.setDomLibrary(aCustomLibrary);</code></pre>
<h3 id="utilities"><a href="#TOC">Utilities</a></h3>
<p>Underscore.js is heavily used in Backbone behind the scenes for everything from object extension through to event binding. As the entire library is generally included, we get free access to a number of useful utilities we can use on Collections such as filtering <code>_.filter()</code>, sorting <code>_.sortBy()</code>, mapping <code>_.map()</code> and so on.</p>
<p>From the source:</p>
<p>``` // Underscore methods that we want to implement on the Collection. var methods = [<q>forEach</q>, <q>each</q>, <q>map</q>, <q>reduce</q>, <q>reduceRight</q>, <q>find</q>, <q>detect</q>, <q>filter</q>, <q>select</q>, <q>reject</q>, <q>every</q>, <q>all</q>, <q>some</q>, <q>any</q>, <q>include</q>, <q>contains</q>, <q>invoke</q>, <q>max</q>, <q>min</q>, <q>sortBy</q>, <q>sortedIndex</q>, <q>toArray</q>, <q>size</q>, <q>first</q>, <q>initial</q>, <q>rest</q>, <q>last</q>, <q>without</q>, <q>indexOf</q>, <q>shuffle</q>, <q>lastIndexOf</q>, <q>isEmpty</q>, <q>groupBy</q>];</p>
<p>// Mix in each Underscore method as a proxy to Collection#models. _.each(methods, function(method) { Collection.prototype[method] = function() { return <em>[method].apply(</em>, [this.models].concat(_.toArray(arguments))); }; ```</p>
<p>However, for a complete linked list of methods supported, see the <a href="http://backbonejs.org/#Collection-Underscore-Methods">official documentation</a>.</p>
<h3 id="restful-persistence"><a href="#TOC">RESTFul persistence</a></h3>
<p>Models and collections in Backbone can be <q>sync</q>ed with the server using the <code>fetch</code>, <code>save</code> and <code>destroy</code> methods. All of these methods delegate back to the <code>Backbone.sync</code> function, which actually wraps jQuery/Zepto’s <code>$.ajax</code> function, calling GET, POST and DELETE for the respective persistence methods on Backbone models.</p>
<p>From the the source for <code>Backbone.sync</code>:</p>
<pre><code>var methodMap = {
&#39;create&#39;: &#39;POST&#39;,
&#39;update&#39;: &#39;PUT&#39;,
&#39;delete&#39;: &#39;DELETE&#39;,
&#39;read&#39;: &#39;GET&#39;
};
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
options || (options = {});
// ... Followed by lots of Backbone.js configuration, then..
return $.ajax(_.extend(params, options));</code></pre>
<h3 id="routing"><a href="#TOC">Routing</a></h3>
<p>Calls to <code>Backbone.History.start</code> rely on jQuery/Zepto binding <code>popState</code> or <code>hashchange</code> event listeners back to the window object.</p>
<p>From the source for <code>Backbone.history.start</code>:</p>
<pre><code>// Depending on whether we&#39;re using pushState or hashes, and whether &#39;onhashchange&#39; is
// supported, determine how we check the URL state.
if (this._hasPushState) {
$(window).bind(&#39;popstate&#39;, this.checkUrl);
} else if (this._wantsHashChange &amp;&amp; (&#39;onhashchange&#39; in window) &amp;&amp; !oldIE) {
$(window).bind(&#39;hashchange&#39;, this.checkUrl);
...</code></pre>
<p><code>Backbone.History.stop</code> similarly uses your DOM manipulation library to unbind these event listeners.</p>
<h2 id="namespacing"><a href="#TOC">Namespacing</a></h2>
<p>When learning how to use Backbone, an important and commonly overlooked area by tutorials is namespacing. If you already have experience with namespacing in JavaScript, the following section will provide some advice on how to specifically apply concepts you know to Backbone, however I will also be covering explanations for beginners to ensure everyone is on the same page.</p>
<h4 id="what-is-namespacing"><a href="#TOC">What is namespacing?</a></h4>
<p>The basic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They’re important as it’s best to safeguard your code from breaking in the event of another script on the page using the same variable names as you are. As a good <q>citizen</q> of the global namespace, it’s also imperative that you do your best to similarly not prevent other developer’s scripts executing due to the same issues.</p>
<p>JavaScript doesn’t really have built-in support for namespaces like other languages, however it does have closures which can be used to achieve a similar effect.</p>
<p>In this section we’ll be taking a look shortly at some examples of how you can namespace your models, views, routers and other components specifically. The patterns we’ll be examining are:</p>
<ul>
<li>Single global variables</li>
<li>Object Literals</li>
<li>Nested namespacing</li>
</ul>
<p><strong>Single global variables</strong></p>
<p>One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication = (<span class="kw">function</span>(){
<span class="kw">function</span>(){
<span class="co">// ...</span>
},
<span class="kw">return</span> {
<span class="co">// ...</span>
}
})();</code></pre>
<p>You’ve probably seen this technique before. A Backbone-specific example might look like this:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myViews = (<span class="kw">function</span>(){
<span class="kw">return</span> {
<span class="dt">TodoView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
<span class="dt">TodosView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. }),
<span class="dt">AboutView</span>: <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({ .. });
<span class="co">//etc.</span>
};
})();</code></pre>
<p>Here we can return a set of views, but the same technique could return an entire collection of models, views and routers depending on how you decide to structure your application. Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.</p>
<p>One solution to this problem, as mentioned by Peter Michaux, is to use prefix namespacing. It’s a simple concept at heart, but the idea is you select a common prefix name (in this example, <code>myApplication_</code>) and then define any methods, variables or other objects after the prefix.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> myApplication_todoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({}),
myApplication_todosView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({});</code></pre>
<p>This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow.</p>
<p>For more on Peter’s views about the single global variable pattern, read his <a href="http://michaux.ca/articles/javascript-namespacing">excellent post on them</a>.</p>
<p>Note: There are several other variations on the single global variable pattern out in the wild, however having reviewed quite a few, I felt the prefixing approach applied best to Backbone.</p>
<p><strong>Object Literals</strong></p>
<p>Object Literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They’re beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, Object Literals often also take into account tests for the existence of a variable by the same name, which helps reduce the chances of collision.</p>
<p>This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/* Doesn&#39;t check for existence of myApplication */</span>
<span class="kw">var</span> myApplication = {};
<span class="co">/*</span>
<span class="co">Does check for existence. If already defined, we use that instance.</span>
<span class="co">Option 1: if(!myApplication) myApplication = {};</span>
<span class="co">Option 2: var myApplication = myApplication || {};</span>
<span class="co">We can then populate our object literal to support models, views and collections (or any data, really):</span>
<span class="co">*/</span>
<span class="kw">var</span> myApplication = {
<span class="dt">models </span>: {},