/index.html
HTML | 4287 lines | 3754 code | 533 blank | 0 comment | 0 complexity | 61c0d4bb072abbf450d73a35c14241e2 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="chrome=1" />
- <meta name="viewport" content="width=device-width">
- <link rel="canonical" href="http://backbonejs.org" />
- <link rel="icon" href="docs/images/favicon.ico" />
- <title>Backbone.js</title>
- <style>
- body {
- font-size: 14px;
- line-height: 22px;
- font-family: Helvetica Neue, Helvetica, Arial;
- background: #f4f4f4 url(docs/images/background.png);
- }
- .interface {
- font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
- }
- div#sidebar {
- background: #fff;
- position: fixed;
- z-index: 10;
- top: 0; left: 0; bottom: 0;
- width: 200px;
- overflow-y: auto;
- overflow-x: hidden;
- -webkit-overflow-scrolling: touch;
- padding: 15px 0 30px 30px;
- border-right: 1px solid #bbb;
- box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
- }
- a.toc_title, a.toc_title:visited {
- display: block;
- color: black;
- font-weight: bold;
- margin-top: 15px;
- }
- a.toc_title:hover {
- text-decoration: underline;
- }
- #sidebar .version {
- font-size: 10px;
- font-weight: normal;
- }
- ul.toc_section {
- font-size: 11px;
- line-height: 14px;
- margin: 5px 0 0 0;
- padding-left: 0px;
- list-style-type: none;
- font-family: Lucida Grande;
- }
- .toc_section li {
- cursor: pointer;
- margin: 0 0 3px 0;
- }
- .toc_section li a {
- text-decoration: none;
- color: black;
- }
- .toc_section li a:hover {
- text-decoration: underline;
- }
- div.container {
- position: relative;
- width: 550px;
- margin: 40px 0 50px 260px;
- }
- img#logo {
- width: 450px;
- height: 80px;
- }
- div.run {
- position: absolute;
- right: 15px;
- width: 26px; height: 18px;
- background: url('docs/images/arrows.png') no-repeat -26px 0;
- }
- div.run:active {
- background-position: -51px 0;
- }
- p, div.container ul {
- margin: 25px 0;
- width: 550px;
- }
- p.warning {
- font-size: 12px;
- line-height: 18px;
- font-style: italic;
- }
- div.container ul {
- list-style: circle;
- padding-left: 15px;
- font-size: 13px;
- line-height: 18px;
- }
- div.container ul li {
- margin-bottom: 10px;
- }
- div.container ul.small {
- font-size: 12px;
- }
- a, a:visited {
- color: #444;
- }
- a:active, a:hover {
- color: #000;
- }
- a.punch {
- display: inline-block;
- background: #4162a8;
- border-top: 1px solid #38538c;
- border-right: 1px solid #1f2d4d;
- border-bottom: 1px solid #151e33;
- border-left: 1px solid #1f2d4d;
- -webkit-border-radius: 4px;
- -moz-border-radius: 4px;
- -ms-border-radius: 4px;
- -o-border-radius: 4px;
- border-radius: 4px;
- -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- color: #fff;
- font: bold 14px "helvetica neue", helvetica, arial, sans-serif;
- line-height: 1;
- margin-bottom: 15px;
- padding: 8px 0 10px 0;
- text-align: center;
- text-shadow: 0px -1px 1px #1e2d4d;
- text-decoration: none;
- width: 225px;
- -webkit-background-clip: padding-box; }
- a.punch:hover {
- -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -ms-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- -o-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
- cursor: pointer; }
- a.punch:active {
- -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
- -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
- -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
- -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
- box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
- margin-top: 5px; margin-bottom: 10px }
- a img {
- border: 0;
- }
- h1, h2, h3, h4, h5, h6 {
- padding-top: 20px;
- }
- h2 {
- font-size: 22px;
- }
- b.header {
- font-size: 18px;
- line-height: 35px;
- }
- span.alias {
- font-size: 14px;
- font-style: italic;
- margin-left: 20px;
- }
- table {
- margin: 15px 0 0; padding: 0;
- }
- tr, td {
- margin: 0; padding: 0;
- }
- td {
- padding: 0px 15px 5px 0;
- }
- table .rule {
- height: 1px;
- background: #ccc;
- margin: 5px 0;
- }
- code, pre, tt {
- font-family: Monaco, Consolas, "Lucida Console", monospace;
- font-size: 12px;
- line-height: 18px;
- font-style: normal;
- }
- tt {
- padding: 0px 3px;
- background: #fff;
- border: 1px solid #ddd;
- zoom: 1;
- }
- code {
- margin-left: 20px;
- }
- pre {
- font-size: 12px;
- padding: 2px 0 2px 15px;
- border: 4px solid #bbb; border-top: 0; border-bottom: 0;
- margin: 0px 0 25px;
- }
- img.example_image {
- margin: 0px auto;
- }
- img.example_retina {
- margin: 20px;
- box-shadow: 0 8px 15px rgba(0,0,0,0.4);
- }
- @media only screen and (-webkit-max-device-pixel-ratio: 1) and (max-width: 600px),
- only screen and (max--moz-device-pixel-ratio: 1) and (max-width: 600px) {
- div#sidebar {
- display: none;
- }
- img#logo {
- max-width: 450px;
- width: 100%;
- height: auto;
- }
- div.container {
- width: auto;
- margin-left: 15px;
- margin-right: 15px;
- }
- p, div.container ul {
- width: auto;
- }
- }
- @media only screen and (-webkit-min-device-pixel-ratio: 1.5) and (max-width: 640px),
- only screen and (-o-min-device-pixel-ratio: 3/2) and (max-width: 640px),
- only screen and (min-device-pixel-ratio: 1.5) and (max-width: 640px) {
- img {
- max-width: 100%;
- height: auto;
- }
- div#sidebar {
- -webkit-overflow-scrolling: initial;
- position: relative;
- width: 90%;
- height: 120px;
- left: 0;
- top: -7px;
- padding: 10px 0 10px 30px;
- border: 0;
- }
- img#logo {
- width: auto;
- height: auto;
- }
- div.container {
- margin: 0;
- width: 100%;
- }
- p, div.container ul {
- max-width: 98%;
- overflow-x: scroll;
- }
- table {
- position: relative;
- }
- tr:first-child td {
- padding-bottom: 25px;
- }
- td.text {
- padding: 0;
- position: absolute;
- left: 0;
- top: 48px;
- }
- tr:last-child td.text {
- top: 122px;
- }
- pre {
- overflow: scroll;
- }
- }
- </style>
- </head>
- <body>
- <div id="sidebar" class="interface">
- <a class="toc_title" href="#">
- Backbone.js <span class="version">(0.9.9)</span>
- </a>
- <ul class="toc_section">
- <li>» <a href="http://github.com/documentcloud/backbone">GitHub Repository</a></li>
- <li>» <a href="docs/backbone.html">Annotated Source</a></li>
- </ul>
- <a class="toc_title" href="#introduction">
- Introduction
- </a>
- <a class="toc_title" href="#upgrading">
- Upgrading
- </a>
- <a class="toc_title" href="#Events">
- Events
- </a>
- <ul class="toc_section">
- <li>– <a href="#Events-on">on</a></li>
- <li>– <a href="#Events-off">off</a></li>
- <li>– <a href="#Events-trigger">trigger</a></li>
- <li>– <a href="#Events-once">once</a></li>
- <li>– <a href="#Events-listenTo">listenTo</a></li>
- <li>– <a href="#Events-stopListening">stopListening</a></li>
- <li>- <a href="#Events-catalog"><b>Catalog of Built-in Events</b></a></li>
- </ul>
- <a class="toc_title" href="#Model">
- Model
- </a>
- <ul class="toc_section">
- <li>– <a href="#Model-extend">extend</a></li>
- <li>– <a href="#Model-constructor">constructor / initialize</a></li>
- <li>– <a href="#Model-get">get</a></li>
- <li>– <a href="#Model-set">set</a></li>
- <li>– <a href="#Model-escape">escape</a></li>
- <li>– <a href="#Model-has">has</a></li>
- <li>– <a href="#Model-unset">unset</a></li>
- <li>– <a href="#Model-clear">clear</a></li>
- <li>– <a href="#Model-id">id</a></li>
- <li>– <a href="#Model-idAttribute">idAttribute</a></li>
- <li>– <a href="#Model-cid">cid</a></li>
- <li>– <a href="#Model-attributes">attributes</a></li>
- <li>– <a href="#Model-changed">changed</a></li>
- <li>– <a href="#Model-defaults">defaults</a></li>
- <li>– <a href="#Model-toJSON">toJSON</a></li>
- <li>– <a href="#Model-sync">sync</a></li>
- <li>– <a href="#Model-fetch">fetch</a></li>
- <li>– <a href="#Model-save">save</a></li>
- <li>– <a href="#Model-destroy">destroy</a></li>
- <li>– <a href="#Model-validate">validate</a></li>
- <li>– <a href="#Model-url">url</a></li>
- <li>– <a href="#Model-urlRoot">urlRoot</a></li>
- <li>– <a href="#Model-parse">parse</a></li>
- <li>– <a href="#Model-clone">clone</a></li>
- <li>– <a href="#Model-isNew">isNew</a></li>
- <li>– <a href="#Model-hasChanged">hasChanged</a></li>
- <li>– <a href="#Model-changedAttributes">changedAttributes</a></li>
- <li>– <a href="#Model-previous">previous</a></li>
- <li>– <a href="#Model-previousAttributes">previousAttributes</a></li>
- </ul>
- <a class="toc_title" href="#Collection">
- Collection
- </a>
- <ul class="toc_section">
- <li>– <a href="#Collection-extend">extend</a></li>
- <li>– <a href="#Collection-model">model</a></li>
- <li>– <a href="#Collection-constructor">constructor / initialize</a></li>
- <li>– <a href="#Collection-models">models</a></li>
- <li>– <a href="#Collection-toJSON">toJSON</a></li>
- <li>– <a href="#Collection-sync">sync</a></li>
- <li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (28)</b></a></li>
- <li>– <a href="#Collection-add">add</a></li>
- <li>– <a href="#Collection-remove">remove</a></li>
- <li>– <a href="#Collection-reset">reset</a></li>
- <li>– <a href="#Collection-update">update</a></li>
- <li>– <a href="#Collection-get">get</a></li>
- <li>– <a href="#Collection-at">at</a></li>
- <li>– <a href="#Collection-push">push</a></li>
- <li>– <a href="#Collection-pop">pop</a></li>
- <li>– <a href="#Collection-unshift">unshift</a></li>
- <li>– <a href="#Collection-shift">shift</a></li>
- <li>– <a href="#Collection-length">length</a></li>
- <li>– <a href="#Collection-comparator">comparator</a></li>
- <li>– <a href="#Collection-sort">sort</a></li>
- <li>– <a href="#Collection-pluck">pluck</a></li>
- <li>– <a href="#Collection-where">where</a></li>
- <li>– <a href="#Collection-url">url</a></li>
- <li>– <a href="#Collection-parse">parse</a></li>
- <li>– <a href="#Collection-clone">clone</a></li>
- <li>– <a href="#Collection-fetch">fetch</a></li>
- <li>– <a href="#Collection-create">create</a></li>
- </ul>
- <a class="toc_title" href="#Router">
- Router
- </a>
- <ul class="toc_section">
- <li>– <a href="#Router-extend">extend</a></li>
- <li>– <a href="#Router-routes">routes</a></li>
- <li>– <a href="#Router-constructor">constructor / initialize</a></li>
- <li>– <a href="#Router-route">route</a></li>
- <li>– <a href="#Router-navigate">navigate</a></li>
- </ul>
- <a class="toc_title" href="#History">
- History
- </a>
- <ul class="toc_section">
- <li>– <a href="#History-start">start</a></li>
- </ul>
- <a class="toc_title" href="#Sync">
- Sync
- </a>
- <ul class="toc_section">
- <li>– <a href="#Sync">Backbone.sync</a></li>
- <li>– <a href="#Sync-ajax">Backbone.ajax</a></li>
- <li>– <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
- <li>– <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
- </ul>
- <a class="toc_title" href="#View">
- View
- </a>
- <ul class="toc_section">
- <li>– <a href="#View-extend">extend</a></li>
- <li>– <a href="#View-constructor">constructor / initialize</a></li>
- <li>– <a href="#View-el">el</a></li>
- <li>– <a href="#View-$el">$el</a></li>
- <li>– <a href="#View-setElement">setElement</a></li>
- <li>– <a href="#View-attributes">attributes</a></li>
- <li>– <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
- <li>– <a href="#View-render">render</a></li>
- <li>– <a href="#View-remove">remove</a></li>
- <li>– <a href="#View-delegateEvents">delegateEvents</a></li>
- <li>– <a href="#View-undelegateEvents">undelegateEvents</a></li>
- </ul>
- <a class="toc_title" href="#Utility">
- Utility
- </a>
- <ul class="toc_section">
- <li>– <a href="#Utility-Backbone-noConflict">Backbone.noConflict</a></li>
- <li>– <a href="#Utility-Backbone-$">Backbone.$</a></li>
- </ul>
- <a class="toc_title" href="#examples">
- Examples
- </a>
- <ul class="toc_section">
- <li>– <a href="#examples-todos">Todos</a></li>
- <li>– <a href="#examples-documentcloud">DocumentCloud</a></li>
- <li>– <a href="#examples-usa-today">USA Today</a></li>
- <li>– <a href="#examples-rdio">Rdio</a></li>
- <li>– <a href="#examples-linkedin">LinkedIn Mobile</a></li>
- <li>– <a href="#examples-hulu">Hulu</a></li>
- <li>– <a href="#examples-flow">Flow</a></li>
- <li>– <a href="#examples-gilt">Gilt Groupe</a></li>
- <li>– <a href="#examples-newsblur">NewsBlur</a></li>
- <li>– <a href="#examples-wordpress">WordPress.com</a></li>
- <li>– <a href="#examples-foursquare">Foursquare</a></li>
- <li>– <a href="#examples-bitbucket">Bitbucket</a></li>
- <li>– <a href="#examples-disqus">Disqus</a></li>
- <li>– <a href="#examples-khan-academy">Khan Academy</a></li>
- <li>– <a href="#examples-do">Do</a></li>
- <li>– <a href="#examples-irccloud">IRCCloud</a></li>
- <li>– <a href="#examples-pitchfork">Pitchfork</a></li>
- <li>– <a href="#examples-spin">Spin</a></li>
- <li>– <a href="#examples-walmart">Walmart Mobile</a></li>
- <li>– <a href="#examples-groupon">Groupon Now!</a></li>
- <li>– <a href="#examples-basecamp">Basecamp</a></li>
- <li>– <a href="#examples-slavery-footprint">Slavery Footprint</a></li>
- <li>– <a href="#examples-stripe">Stripe</a></li>
- <li>– <a href="#examples-airbnb">Airbnb</a></li>
- <li>– <a href="#examples-diaspora">Diaspora</a></li>
- <li>– <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
- <li>- <a href="#examples-artsy">Art.sy</a></li>
- <li>– <a href="#examples-pandora">Pandora</a></li>
- <li>– <a href="#examples-inkling">Inkling</a></li>
- <li>– <a href="#examples-code-school">Code School</a></li>
- <li>– <a href="#examples-cloudapp">CloudApp</a></li>
- <li>– <a href="#examples-seatgeek">SeatGeek</a></li>
- <li>– <a href="#examples-easel">Easel</a></li>
- <li>– <a href="#examples-prose">Prose</a></li>
- <li>- <a href="#examples-jolicloud">Jolicloud</a></li>
- <li>– <a href="#examples-battlefield">Battlefield Play4Free</a></li>
- <li>– <a href="#examples-syllabus">Syllabus</a></li>
- <li>– <a href="#examples-salon">Salon.io</a></li>
- <li>– <a href="#examples-tilemill">TileMill</a></li>
- <li>– <a href="#examples-blossom">Blossom</a></li>
- <li>– <a href="#examples-decide">Decide</a></li>
- <li>– <a href="#examples-trello">Trello</a></li>
- <li>– <a href="#examples-tzigla">Tzigla</a></li>
- </ul>
- <a class="toc_title" href="#faq">
- F.A.Q.
- </a>
- <ul class="toc_section">
- <li>– <a href="#FAQ-why-backbone">Why Backbone?</a></li>
- <li>– <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
- <li>– <a href="#FAQ-nested">Nested Models & Collections</a></li>
- <li>– <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
- <li>– <a href="#FAQ-extending">Extending Backbone</a></li>
- <li>– <a href="#FAQ-mvc">Traditional MVC</a></li>
- <li>– <a href="#FAQ-this">Binding "this"</a></li>
- <li>– <a href="#FAQ-rails">Working with Rails</a></li>
- </ul>
- <a class="toc_title" href="#changelog">
- Change Log
- </a>
- </div>
- <div class="container">
- <p>
- <img id="logo" src="docs/images/backbone.png" alt="Backbone.js" />
- </p>
- <p>
- Backbone.js gives structure to web applications
- by providing <b>models</b> with key-value binding and custom events,
- <b>collections</b> with a rich API of enumerable functions,
- <b>views</b> with declarative event handling, and connects it all to your
- existing API over a RESTful JSON interface.
- </p>
- <p>
- The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
- and the <a href="docs/backbone.html">annotated source code</a> is available,
- as well as an online <a href="test/">test suite</a>,
- an <a href="examples/todos/index.html">example application</a>,
- a <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>
- and a <a href="#examples">long list of real-world projects</a> that use Backbone.
- Backbone is available for use under the <a href="http://github.com/documentcloud/backbone/blob/master/LICENSE">MIT software license</a>.
- </p>
- <p>
- You can report bugs and discuss features on the
- <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
- on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
- <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
- add pages to the <a href="https://github.com/documentcloud/backbone/wiki">wiki</a>
- or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
- </p>
- <p>
- <i>
- Backbone is an open-source component of
- <a href="http://documentcloud.org/">DocumentCloud</a>.
- </i>
- </p>
- <h2 id="downloads">
- Downloads & Dependencies
- <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
- </h2>
- <table>
- <tr>
- <td><a class="punch" href="backbone.js">Development Version (0.9.9)</a></td>
- <td class="text"><i>56kb, Full source, lots of comments</i></td>
- </tr>
- <tr>
- <td><a class="punch" href="backbone-min.js">Production Version (0.9.9)</a></td>
- <td class="text"><i>6.3kb, Packed and gzipped</i></td>
- </tr>
- <tr>
- <td><a class="punch" href="https://raw.github.com/documentcloud/backbone/master/backbone.js">Edge Version (master)</a></td>
- <td>
- <i>Unreleased, use at your own risk</i>
- <a href="https://travis-ci.org/documentcloud/backbone">
- <img width="89" height="13" src="https://travis-ci.org/documentcloud/backbone.png" />
- </a>
- </td>
- </tr>
- </table>
- <p>
- Backbone's only hard dependency is either
- <a href="http://underscorejs.org/">Underscore.js</a> <small>( >= 1.4.3)</small> or
- <a href="http://lodash.com">Lo-Dash</a>.
- For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
- and DOM manipulation with <a href="#View">Backbone.View</a>, include
- <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
- <a href="http://jquery.com">jQuery</a> <small>( >= 1.7.0)</small> or
- <a href="http://zeptojs.com/">Zepto</a>.
- </p>
- <h2 id="introduction">Introduction</h2>
- <p>
- When working on a web application that involves a lot of JavaScript, one
- of the first things you learn is to stop tying your data to the DOM. It's all
- too easy to create JavaScript applications that end up as tangled piles of
- jQuery selectors and callbacks, all trying frantically to keep data in
- sync between the HTML UI, your JavaScript logic, and the database on your
- server. For rich client-side applications, a more structured approach
- is often helpful.
- </p>
- <p>
- With Backbone, you represent your data as
- <a href="#Model">Models</a>, which can be created, validated, destroyed,
- and saved to the server. Whenever a UI action causes an attribute of
- a model to change, the model triggers a <i>"change"</i> event; all
- the <a href="#View">Views</a> that display the model's state can be notified of the
- change, so that they are able to respond accordingly, re-rendering themselves with
- the new information. In a finished Backbone app, you don't have to write the glue
- code that looks into the DOM to find an element with a specific <i>id</i>,
- and update the HTML manually
- — when the model changes, the views simply update themselves.
- </p>
- <p>
- If you're new here, and aren't yet quite sure what Backbone is for, start by
- browsing the <a href="#examples">list of Backbone-based projects</a>.
- </p>
- <p>
- Many of the examples that follow are runnable. Click the <i>play</i> button
- to execute them.
- </p>
- <h2 id="upgrading">Upgrading to Edge</h2>
- <p>
- You're reading the docs for an unreleased version. See the
- <a href="#changelog">change log</a>.
- </p>
- <h2>Upgrading to 0.9.9</h2>
- <p>
- Backbone <b>0.9.9</b> should be considered as a release candidate
- for an upcoming <b>1.0</b>. If you're upgrading from a previous version,
- be sure to check the
- <a href="#changelog">change log</a>. In brief, a few of the larger changes
- are:
- </p>
- <ul>
- <li>
- Most importantly, Backbone events have two new methods:
- <a href="#Events-listenTo">listenTo</a> and
- <a href="#Events-stopListening">stopListening</a>. These are an
- inversion-of-control flavor of the usual <tt>on</tt> and <tt>off</tt>,
- and make it a little easier to clean up <i>all</i> events
- that an object is listening to on other objects. When you destroy Views
- with <a href="#View-remove">view.remove()</a>, this will now be done
- automatically. Note that the usual rules about programming in a garbage
- collected language still apply.
- </li>
- <li>
- HTTP <tt>PATCH</tt> support, via <tt>model.save(attrs, {patch: true})</tt>,
- if you'd like to send only partial updates to the server.
- </li>
- <li>
- An <a href="#Collection-update">update</a> method was added to Collection,
- which should make it easier to perform "smart" syncing updates with the
- server, where models are added or removed, and updated attributes are merged
- as appropriate. If you were previously using <br />
- <tt>collection.fetch({add: true})</tt>,
- try <a href="#Collection-update">update</a> instead.
- </li>
- <li>
- Backbone events now support <a href="#Events-once"</a>once</a>.
- </li>
- </ul>
- <h2 id="Events">Backbone.Events</h2>
- <p>
- <b>Events</b> is a module that can be mixed in to any object, giving the
- object the ability to bind and trigger custom named events. Events do not
- have to be declared before they are bound, and may take passed arguments.
- For example:
- </p>
- <pre class="runnable">
- var object = {};
- _.extend(object, Backbone.Events);
- object.on("alert", function(msg) {
- alert("Triggered " + msg);
- });
- object.trigger("alert", "an event");
- </pre>
- <p>
- For example, to make a handy event dispatcher that can coordinate events
- among different areas of your application: <tt>var dispatcher = _.clone(Backbone.Events)</tt>
- </p>
- <p id="Events-on">
- <b class="header">on</b><code>object.on(event, callback, [context])</code><span class="alias">Alias: bind</span>
- <br />
- Bind a <b>callback</b> function to an object. The callback will be invoked
- whenever the <b>event</b> is fired.
- If you have a large number of different events on a page, the convention is to use colons to
- namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>.
- The event string may also be a space-delimited list of several events...
- </p>
- <pre>
- book.on("change:title change:author", ...);
- </pre>
- <p>
- To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
- pass the optional third argument: <tt>model.on('change', this.render, this)</tt>
- </p>
- <p>
- Callbacks bound to the special
- <tt>"all"</tt> event will be triggered when any event occurs, and are passed
- the name of the event as the first argument. For example, to proxy all events
- from one object to another:
- </p>
- <pre>
- proxy.on("all", function(eventName) {
- object.trigger(eventName);
- });
- </pre>
- <p>
- All Backbone event methods also support an event map syntax, as an alternative
- to positional arguments:
- </p>
- <pre>
- book.on({
- "change:title": titleView.update,
- "change:author": authorPane.update,
- "destroy": bookView.remove
- });
- </pre>
- <p id="Events-off">
- <b class="header">off</b><code>object.off([event], [callback], [context])</code><span class="alias">Alias: unbind</span>
- <br />
- Remove a previously-bound <b>callback</b> function from an object. If no
- <b>context</b> is specified, all of the versions of the callback with
- different contexts will be removed. If no
- callback is specified, all callbacks for the <b>event</b> will be
- removed. If no event is specified, callbacks for <i>all</i> events
- will be removed.
- </p>
- <pre>
- // Removes just the `onChange` callback.
- object.off("change", onChange);
- // Removes all "change" callbacks.
- object.off("change");
- // Removes the `onChange` callback for all events.
- object.off(null, onChange);
- // Removes all callbacks for `context` for all events.
- object.off(null, null, context);
- // Removes all callbacks on `object`.
- object.off();
- </pre>
- <p>
- Note that calling <tt>model.off()</tt>, for example, will indeed remove <i>all</i> events
- on the model — including events that Backbone uses for internal bookkeeping.
- </p>
- <p id="Events-trigger">
- <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
- <br />
- Trigger callbacks for the given <b>event</b>, or space-delimited list of events.
- Subsequent arguments to <b>trigger</b> will be passed along to the
- event callbacks.
- </p>
- <p id="Events-once">
- <b class="header">once</b><code>object.once(event, callback, [context])</code>
- <br />
- Just like <a href="#Events-on">on</a>, but causes the bound callback to only
- fire once before being removed. Handy for saying "the next time that X happens, do this".
- </p>
- <p id="Events-listenTo">
- <b class="header">listenTo</b><code>object.listenTo(other, event, callback)</code>
- <br />
- Tell an <b>object</b> to listen to a particular event on an <b>other</b> object.
- The advantage of using this form, instead of <tt>other.on(event, callback)</tt>,
- is that <b>listenTo</b> allows the <b>object</b> to keep track of the events,
- and they can be removed all at once later on.
- </p>
- <pre>
- view.listenTo(model, 'change', view.render);
- </pre>
- <p id="Events-stopListening">
- <b class="header">stopListening</b><code>object.stopListening([other], [event], [callback])</code>
- <br />
- Tell an <b>object</b> to stop listening to events. Either call
- <b>stopListening</b> with no arguments to have the <b>object</b> remove
- all of its <a href="#Events-listenTo">registered</a> callbacks ... or be more
- precise by telling it to remove just the events it's listening to on a
- specific object, or a specific event, or just a specific callback.
- </p>
- <pre>
- view.stopListening();
- view.stopListening(model);
- </pre>
- <p id="Events-catalog">
- <b class="header">Catalog of Events</b>
- <br />
- Here's the complete list of built-in Backbone events, with arguments.
- You're also free to trigger your own events on Models, Collections and
- Views as you see fit. The <tt>Backbone</tt> object itself mixes in <tt>Events</tt>,
- and can be used to emit any global events that your application needs.
- </p>
- <ul class="small">
- <li><b>"add"</b> (model, collection, options) — when a model is added to a collection. </li>
- <li><b>"remove"</b> (model, collection, options) — when a model is removed from a collection. </li>
- <li><b>"reset"</b> (collection, options) — when the collection's entire contents have been replaced. </li>
- <li><b>"sort"</b> (collection, options) — when the collection has been re-sorted. </li>
- <li><b>"change"</b> (model, options) — when a model's attributes have changed. </li>
- <li><b>"change:[attribute]"</b> (model, value, options) — when a specific attribute has been updated. </li>
- <li><b>"destroy"</b> (model, collection, options) — when a model is <a href="#Model-destroy">destroyed</a>. </li>
- <li><b>"request"</b> (model, xhr, options) — when a model (or collection) has started a request to the server. </li>
- <li><b>"sync"</b> (model, resp, options) — when a model has been successfully synced with the server. </li>
- <li><b>"error"</b> (model, xhr, options) — when a model's <a href="#Model-save">save</a> call fails on the server. </li>
- <li><b>"invalid"</b> (model, error, options) — when a model's <a href="#Model-validate">validation</a> fails on the client. </li>
- <li><b>"route:[name]"</b> (params) — Fired by the router when a specific route is matched.</li>
- <li><b>"route"</b> (router, route, params) — Fired by history (or router) when <i>any</i> route has been matched.</li>
- <li><b>"all"</b> — this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
- </ul>
- <h2 id="Model">Backbone.Model</h2>
- <p>
- <b>Models</b> are the heart of any JavaScript application, containing
- the interactive data as well as a large part of the logic surrounding it:
- conversions, validations, computed properties, and access control. You
- extend <b>Backbone.Model</b> with your domain-specific methods, and
- <b>Model</b> provides a basic set of functionality for managing changes.
- </p>
- <p>
- The following is a contrived example, but it demonstrates defining a model
- with a custom method, setting an attribute, and firing an event keyed
- to changes in that specific attribute.
- After running this code once, <tt>sidebar</tt> will be
- available in your browser's console, so you can play around with it.
- </p>
- <pre class="runnable">
- var Sidebar = Backbone.Model.extend({
- promptColor: function() {
- var cssColor = prompt("Please enter a CSS color:");
- this.set({color: cssColor});
- }
- });
- window.sidebar = new Sidebar;
- sidebar.on('change:color', function(model, color) {
- $('#sidebar').css({background: color});
- });
- sidebar.set({color: 'white'});
- sidebar.promptColor();
- </pre>
- <p id="Model-extend">
- <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
- <br />
- To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
- and provide instance <b>properties</b>, as well as optional
- <b>classProperties</b> to be attached directly to the constructor function.
- </p>
- <p>
- <b>extend</b> correctly sets up the prototype chain, so subclasses created
- with <b>extend</b> can be further extended and subclassed as far as you like.
- </p>
- <pre>
- var Note = Backbone.Model.extend({
- initialize: function() { ... },
- author: function() { ... },
- coordinates: function() { ... },
- allowedToEdit: function(account) {
- return true;
- }
- });
- var PrivateNote = Note.extend({
- allowedToEdit: function(account) {
- return account.owns(this);
- }
- });
- </pre>
- <p class="warning">
- Brief aside on <tt>super</tt>: JavaScript does not provide
- a simple way to call super — the function of the same name defined
- higher on the prototype chain. If you override a core function like
- <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
- parent object's implementation, you'll have to explicitly call it, along these lines:
- </p>
- <pre>
- var Note = Backbone.Model.extend({
- set: function(attributes, options) {
- Backbone.Model.prototype.set.apply(this, arguments);
- ...
- }
- });
- </pre>
- <p id="Model-constructor">
- <b class="header">constructor / initialize</b><code>new Model([attributes], [options])</code>
- <br />
- When creating an instance of a model, you can pass in the initial values
- of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
- model. If you define an <b>initialize</b> function, it will be invoked when
- the model is created.
- </p>
- <pre>
- new Book({
- title: "One Thousand and One Nights",
- author: "Scheherazade"
- });
- </pre>
- <p>
- In rare cases, if you're looking to get fancy,
- you may want to override <b>constructor</b>, which allows
- you to replace the actual constructor function for your model.
- </p>
- <p>
- If you pass a <tt>{collection: ...}</tt> as the <b>options</b>, the model
- gains a <tt>collection</tt> property that will be used to indicate which
- collection the model belongs to, and is used to help compute the model's
- <a href="#Model-url">url</a>. The <tt>model.collection</tt> property is
- otherwise added automatically when you first add a model to a collection.
- </p>
- <p id="Model-get">
- <b class="header">get</b><code>model.get(attribute)</code>
- <br />
- Get the current value of an attribute from the model. For example:
- <tt>note.get("title")</tt>
- </p>
- <p id="Model-set">
- <b class="header">set</b><code>model.set(attributes, [options])</code>
- <br />
- Set a hash of attributes (one or many) on the model. If any of the attributes
- change the model's state, a <tt>"change"</tt> event will be triggered, unless
- <tt>{silent: true}</tt> is passed as an option. Change events for specific
- attributes are also triggered, and you can bind to those as well, for example:
- <tt>change:title</tt>, and <tt>change:content</tt>. You may also pass
- individual keys and values.
- </p>
- <pre>
- note.set({title: "March 20", content: "In his eyes she eclipses..."});
- book.set("title", "A Scandal in Bohemia");
- </pre>
- <p>
- If the model has a <a href="#Model-validate">validate</a> method,
- it will be validated before the attributes are set, no changes will
- occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
- Otherwise, <b>set</b> returns a reference to the model.
- You may also pass an <tt>error</tt>
- callback in the options, which will be invoked alongside the
- <tt>"error"</tt> event, should validation fail.
- </p>
- <p id="Model-escape">
- <b class="header">escape</b><code>model.escape(attribute)</code>
- <br />
- Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
- of a model's attribute. If you're interpolating data from the model into
- HTML, using <b>escape</b> to retrieve attributes will prevent
- <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
- </p>
- <pre class="runnable">
- var hacker = new Backbone.Model({
- name: "<script>alert('xss')</script>"
- });
- alert(hacker.escape('name'));
- </pre>
- <p id="Model-has">
- <b class="header">has</b><code>model.has(attribute)</code>
- <br />
- Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
- value.
- </p>
- <pre>
- if (note.has("title")) {
- ...
- }
- </pre>
- <p id="Model-unset">
- <b class="header">unset</b><code>model.unset(attribute, [options])</code>
- <br />
- Remove an attribute by deleting it from the internal attributes hash.
- Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
- </p>
- <p id="Model-clear">
- <b class="header">clear</b><code>model.clear([options])</code>
- <br />
- Removes all attributes from the model, including the <tt>id</tt> attribute. Fires a <tt>"change"</tt> event unless
- <tt>silent</tt> is passed as an option.
- </p>
- <p id="Model-id">
- <b class="header">id</b><code>model.id</code>
- <br />
- A special property of models, the <b>id</b> is an arbitrary string
- (integer id or UUID). If you set the <b>id</b> in the
- attributes hash, it will be copied onto the model as a direct property.
- Models can be retrieved by id from collections, and the id is used to generate
- model URLs by default.
- </p>
- <p id="Model-idAttribute">
- <b class="header">idAttribute</b><code>model.idAttribute</code>
- <br />
- A model's unique identifier is stored under the <tt>id</tt> attribute.
- If you're directly communicating with a backend (CouchDB, MongoDB) that uses
- a different unique key, you may set a Model's <tt>idAttribute</tt> to
- transparently map from that key to <tt>id</tt>.
- <pre class="runnable">
- var Meal = Backbone.Model.extend({
- idAttribute: "_id"
- });
- var cake = new Meal({ _id: 1, name: "Cake" });
- alert("Cake id: " + cake.id);
- </pre>
- </p>
- <p id="Model-cid">
- <b class="header">cid</b><code>model.cid</code>
- <br />
- A special property of models, the <b>cid</b> or client id is a unique identifier
- automatically assigned to all models when they're first created. Client ids
- are handy when the model has not yet been saved to the server, and does not
- yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
- </p>
- <p id="Model-attributes">
- <b class="header">attributes</b><code>model.attributes</code>
- <br />
- The <b>attributes</b> property is the internal hash containing the model's
- state — usually (but not necessarily) a form of the JSON object
- representing the model data on the server. It's often a straightforward
- serialization of a row from the database, but it could also be client-side
- computed state.
- </p>
- <p>
- Please use <a href="#Model-set">set</a> to update the <b>attributes</b>
- instead of modifying them directly. If you'd like to retrieve and munge a
- copy of the model's attributes, use <a href="#Model-toJSON">toJSON</a>
- instead.
- </p>
- <p class="warning">
- Due to the fact that <a href="#Events">Events</a> accepts space separated
- lists of events, attribute names should not include spaces.
- </p>
- <p id="Model-changed">
- <b class="header">changed</b><code>model.changed</code>
- <br />
- The <b>changed</b> property is the internal hash containing all the attributes
- that have changed since the last <tt>"change"</tt> event was triggered.
- Please do not update <b>changed</b> directly. Its state is maintained internally
- by <a href="#Model-set">set</a> and <a href="#Model-change">change</a>.
- A copy of <b>changed</b> can be acquired from
- <a href="#Model-changedAttributes">changedAttributes</a>.
- </p>
- <p id="Model-defaults">
- <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
- <br />
- The <b>defaults</b> hash (or function) can be used to specify the default
- attributes for your model. When creating an instance of the model,
- any unspecified attributes will be set to their default value.
- </p>
- <pre class="runnable">
- var Meal = Backbone.Model.extend({
- defaults: {
- "appetizer": "caesar salad",
- "entree": "ravioli",
- "dessert": "cheesecake"
- }
- });
- alert("Dessert will be " + (new Meal).get('dessert'));
- </pre>
- <p class="warning">
- Remember that in JavaScript, objects are passed by reference, so if you
- include an object as a default value, it will be shared among all instances.
- Instead, define <b>defaults</b> as a function.
- </p>
- <p id="Model-toJSON">
- <b class="header">toJSON</b><code>model.toJSON()</code>
- <br />
- Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
- This can be used for persistence, serialization, or for augmentation before
- being handed off to a view. The name of this method is a bit confusing, as
- it doesn't actually return a JSON string — but I'm afraid that it's
- the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
- </p>
- <pre class="runnable">
- var artist = new Backbone.Model({
- firstName: "Wassily",
- lastName: "Kandinsky"
- });
- artist.set({birthday: "December 16, 1866"});
- alert(JSON.stringify(artist));
- </pre>
- <p id="Model-sync">
- <b class="header">sync</b><code>model.sync(method, model, [options])</code>
- <br />
- Uses <a href="#Sync">Backbone.sync</a> to persist the state of a model to
- the server. Can be overridden for custom behavior.
- </p>
- <p id="Model-fetch">
- <b class="header">fetch</b><code>model.fetch([options])</code>
- <br />
- Resets the model's state from the server by delegating to
- <a href="#Sync">Backbone.sync</a>. Returns a
- <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>.
- Useful if the model has never
- been populated with data, or if you'd like to ensure that you have the
- latest server state. A <tt>"change"</tt> event will be triggered if the
- server's state differs from the current attributes. Accepts
- <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
- are passed <tt>(model, response, options)</tt>
- and <tt>(model, xhr, options)</tt> as arguments, respectively.
- </p>
- <pre>
- // Poll every 10 seconds to keep the channel model up-to-date.
- setInterval(function() {
- channel.fetch();
- }, 10000);
- </pre>
- <p id="Model-save">
- <b class="header">save</b><code>model.save([attributes], [options])</code>
- <br />
- Save a model to your database (or alternative persistence layer),
- by delegating to <a href="#Sync">Backbone.sync</a>. Returns a
- <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> if
- validation is successful and <tt>false</tt> otherwise. The <b>attributes</b>
- hash (as in <a href="#Model-set">set</a>) should contain the attributes
- you'd like to change — keys that aren't mentioned won't be altered — but,
- a <i>complete representation</i> of the resource will be sent to the server.
- As with <tt>set</tt>, you may pass individual keys and values instead of a hash.
- If the model has a <a href="#Model-validate">validate</a>
- method, and validation fails, the model will not be saved. If the model
- <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
- (HTTP <tt>POST</tt>), if the model already
- exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
- </p>
- <p>
- If instead, you'd only like the <i>changed</i> attributes to be sent to the
- server, call <tt>model.save(attrs, {patch: true})</tt>. You'll get an HTTP
- <tt>PATCH</tt> request to the server with just the passed-in attributes.
- </p>
- <p>
- Calling <tt>save</tt> with new attributes will cause a <tt>"change"</tt>
- event immediately, a <tt>"request"</tt> event as the Ajax request begins to
- go to the server, and a <tt>"sync"</tt> event after the server has acknowledged
- the successful change. Pass <tt>{wait: true}</tt> if you'd like to wait
- for the server before setting the new attributes on the model.
- </p>
- <p>
- In the following example, notice how our overridden version
- of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
- the first time the model is saved and an <tt>"update"</tt>
- request the second time.
- </p>
- <pre class="runnable">
- Backbone.sync = function(method, model) {
- alert(method + ": " + JSON.stringify(model));
- model.id = 1;
- };
- var book = new Backbone.Model({
- title: "The Rough Riders",
- author: "Theodore Roosevelt"
- });
- book.save();
- book.save({author: "Teddy"});
- </pre>
- <p>
- <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
- options hash, which are passed <tt>(model, response, options)</tt> and
- <tt>(model, xhr, options)</tt> as arguments, respectively.
- The <tt>error</tt> callback will also be invoked if the model has a
- <tt>validate</tt> method, and validation fails. If a server-side
- validation fails, return a non-<tt>200</tt> HTTP response code, along with
- an error response in text or JSON.
- </p>
- <pre>
- book.save("author", "F.D.R.", {error: function(){ ... }});
- </pre>
- <p id="Model-destroy">
- <b class="header">destroy</b><code>model.destroy([options])</code>
- <br />
- Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
- request to <a href="#Sync">Backbone.sync</a>. Returns a
- <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> object, or
- <tt>false</tt> if the model <a href="#Model-isNew">isNew</a>. Accepts
- <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
- are passed <tt>(model, response, options)</tt> and <tt>(model, xhr, options)</tt>
- as arguments, respectively.
- Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
- through any collections that contain it, a <tt>"request"</tt> event as it
- begins the Ajax request to the server, and a <tt>"sync"</tt> event, after
- the server has successfully acknowledged the model's deletion. Pass
- <tt>{wait: true}</tt> if you'd like to wait for the server to respond
- before removing the model from the collection.
- </p>
- <pre>
- book.destroy({success: function(model, response) {
- ...
- }});
- </pre>
- <p id="Model-validate">
- <b class="header">validate</b><code>model.validate(attributes, options)</code>
- <br />
- This method is left undefined, and you're encouraged to override it with
- your custom validation logic, if you have any that can be performed
- in JavaScript. By default <b>validate</b> is called before
- <tt>save</tt>, but can also be called before <tt>set</tt> if
- <tt>{validate:true}</tt> is passed. The <b>validate</b> method is passed
- the model attributes, as well as the options from <tt>set</tt> or <tt>save</tt>.
- If the attributes are valid, don't return anything from <b>validate</b>;
- if they are invalid, return an error of your choosing. It
- can be as simple as a string error message to be displayed, or a complete
- error object that describes the error programmatically. If <b>validate</b>
- returns an error, <tt>set</tt> and <tt>save</tt> will not continue, and the
- model attributes will not be modified.
- Failed validations trigger an <tt>"error"</tt> event.
- </p>
- <pre class="runnable">
- var Chapter = Backbone.Model.extend({
- validate: function(attrs, options) {
- if (attrs.end < attrs.start) {
- return "can't end before it starts";
- }
- }
- });
- var one = new Chapter({
- title : "Chapter One: The Beginning"
- });
- one.on("error", function(model, error) {
- alert(model.get("title") + " " + error);
- });
- one.set({
- start: 15,
- end: 10
- });
- </pre>
- <p>
- <tt>"error"</tt> events are useful for providing coarse-grained error
- messages at the model or collection level. An <tt>error</tt> callback can
- can also be specified in the options…
Large files files are truncated, but you can click here to view the full file