PageRenderTime 84ms CodeModel.GetById 6ms app.highlight 60ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

https://github.com/djmitche/backbone
HTML | 2203 lines | 1892 code | 311 blank | 0 comment | 0 complexity | a0f2db380c21f28902d4a18121a2c1f1 MD5 | raw file
   1<!DOCTYPE HTML>
   2<html>
   3<head>
   4  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
   5  <meta http-equiv="X-UA-Compatible" content="chrome=1">
   6  <title>Backbone.js</title>
   7  <style>
   8    body {
   9      font-size: 14px;
  10      line-height: 22px;
  11      font-family: Helvetica Neue, Helvetica, Arial;
  12      background: #f4f4f4 url(docs/images/background.png);
  13    }
  14    .interface {
  15      font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  16    }
  17    div#sidebar {
  18      background: #fff;
  19      position: fixed;
  20      top: 0; left: 0; bottom: 0;
  21      width: 200px;
  22      overflow-y: auto;
  23      overflow-x: hidden;
  24      padding: 15px 0 30px 30px;
  25      border-right: 1px solid #ddd;
  26      box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  27    }
  28      a.toc_title, a.toc_title:visited {
  29        display: block;
  30        color: black;
  31        font-weight: bold;
  32        margin-top: 15px;
  33      }
  34        div.toc_title:hover {
  35          text-decoration: underline;
  36        }
  37        #sidebar .version {
  38          font-size: 10px;
  39          font-weight: normal;
  40        }
  41      ul.toc_section {
  42        font-size: 11px;
  43        line-height: 14px;
  44        margin: 5px 0 0 0;
  45        padding-left: 0px;
  46        list-style-type: none;
  47        font-family: Lucida Grande;
  48      }
  49        .toc_section li {
  50          cursor: pointer;
  51          margin: 0 0 3px 0;
  52        }
  53          .toc_section li a {
  54            color: black;
  55          }
  56    div.container {
  57      position: relative;
  58      width: 550px;
  59      margin: 40px 0 50px 260px;
  60    }
  61    div.run {
  62      position: absolute;
  63      right: 15px;
  64      width: 26px; height: 18px;
  65      background: url('docs/images/arrows.png') no-repeat -26px 0;
  66    }
  67      div.run:active {
  68        background-position: -51px 0;
  69      }
  70    p, div.container ul {
  71      margin: 20px 0;
  72      width: 550px;
  73    }
  74      p.warning {
  75        font-size: 12px;
  76        line-height: 18px;
  77        font-style: italic;
  78      }
  79      div.container ul {
  80        list-style: circle;
  81        font-size: 12px;
  82        padding-left: 15px;
  83      }
  84    a, a:visited {
  85      color: #444;
  86      text-decoration: none;
  87    }
  88    a:active, a:hover {
  89      color: #000;
  90      text-decoration: underline;
  91    }
  92    a img {
  93      border: 0;
  94    }
  95    h1, h2, h3, h4, h5, h6 {
  96      padding-top: 20px;
  97    }
  98      h2 {
  99        font-size: 20px;
 100      }
 101    b.header {
 102      font-size: 16px;
 103      line-height: 30px;
 104    }
 105    span.alias {
 106      font-size: 14px;
 107      font-style: italic;
 108      margin-left: 20px;
 109    }
 110    table {
 111      margin: 15px 0 0; padding: 0;
 112    }
 113      tr, td {
 114        margin: 0; padding: 0;
 115      }
 116        td {
 117          padding: 0px 15px 5px 0;
 118        }
 119    code, pre, tt {
 120      font-family: Monaco, Consolas, "Lucida Console", monospace;
 121      font-size: 12px;
 122      line-height: 18px;
 123      font-style: normal;
 124    }
 125      tt {
 126        padding: 0px 3px;
 127        background: #fff;
 128        border: 1px solid #ddd;
 129        zoom: 1;
 130      }
 131      code {
 132        margin-left: 20px;
 133      }
 134      pre {
 135        font-size: 12px;
 136        padding: 2px 0 2px 15px;
 137        border: 4px solid #bbb; border-top: 0; border-bottom: 0;
 138        margin: 0px 0 30px;
 139      }
 140      img.example_image {
 141        margin: 0px auto 30px;
 142      }
 143  </style>
 144</head>
 145<body>
 146
 147  <div id="sidebar" class="interface">
 148
 149    <a class="toc_title" href="#">
 150      Backbone.js <span class="version">(0.3.3)</span>
 151    </a>
 152
 153    <a class="toc_title" href="#Introduction">
 154      Introduction
 155    </a>
 156
 157    <a class="toc_title" href="#Events">
 158      Events
 159    </a>
 160    <ul class="toc_section">
 161      <li><a href="#Events-bind">bind</a></li>
 162      <li><a href="#Events-unbind">unbind</a></li>
 163      <li><a href="#Events-trigger">trigger</a></li>
 164    </ul>
 165
 166    <a class="toc_title" href="#Model">
 167      Model
 168    </a>
 169    <ul class="toc_section">
 170      <li><a href="#Model-extend">extend</a></li>
 171      <li><a href="#Model-constructor">constructor / initialize</a></li>
 172      <li><a href="#Model-get">get</a></li>
 173      <li><a href="#Model-set">set</a></li>
 174      <li><a href="#Model-escape">escape</a></li>
 175      <li><a href="#Model-has">has</a></li>
 176      <li><a href="#Model-unset">unset</a></li>
 177      <li><a href="#Model-clear">clear</a></li>
 178      <li><a href="#Model-id">id</a></li>
 179      <li><a href="#Model-cid">cid</a></li>
 180      <li><a href="#Model-attributes">attributes</a></li>
 181      <li><a href="#Model-defaults">defaults</a></li>
 182      <li>- <a href="#Model-toJSON">toJSON</a></li>
 183      <li><a href="#Model-fetch">fetch</a></li>
 184      <li><a href="#Model-save">save</a></li>
 185      <li><a href="#Model-destroy">destroy</a></li>
 186      <li><a href="#Model-validate">validate</a></li>
 187      <li><a href="#Model-url">url</a></li>
 188      <li><a href="#Model-urlRoot">urlRoot</a></li>
 189      <li><a href="#Model-parse">parse</a></li>
 190      <li><a href="#Model-clone">clone</a></li>
 191      <li><a href="#Model-isNew">isNew</a></li>
 192      <li><a href="#Model-change">change</a></li>
 193      <li><a href="#Model-hasChanged">hasChanged</a></li>
 194      <li><a href="#Model-changedAttributes">changedAttributes</a></li>
 195      <li><a href="#Model-previous">previous</a></li>
 196      <li><a href="#Model-previousAttributes">previousAttributes</a></li>
 197    </ul>
 198
 199    <a class="toc_title" href="#Collection">
 200      Collection
 201    </a>
 202    <ul class="toc_section">
 203      <li><a href="#Collection-extend">extend</a></li>
 204      <li><a href="#Collection-model">model</a></li>
 205      <li><a href="#Collection-constructor">constructor / initialize</a></li>
 206      <li><a href="#Collection-models">models</a></li>
 207      <li><a href="#Collection-toJSON">toJSON</a></li>
 208      <li><a href="#Collection-Underscore-Methods"><b>Underscore Methods (25)</b></a></li>
 209      <li><a href="#Collection-add">add</a></li>
 210      <li><a href="#Collection-remove">remove</a></li>
 211      <li><a href="#Collection-get">get</a></li>
 212      <li><a href="#Collection-getByCid">getByCid</a></li>
 213      <li><a href="#Collection-at">at</a></li>
 214      <li><a href="#Collection-length">length</a></li>
 215      <li><a href="#Collection-comparator">comparator</a></li>
 216      <li><a href="#Collection-sort">sort</a></li>
 217      <li><a href="#Collection-pluck">pluck</a></li>
 218      <li><a href="#Collection-url">url</a></li>
 219      <li><a href="#Collection-parse">parse</a></li>
 220      <li><a href="#Collection-fetch">fetch</a></li>
 221      <li><a href="#Collection-refresh">refresh</a></li>
 222      <li><a href="#Collection-create">create</a></li>
 223    </ul>
 224
 225    <a class="toc_title" href="#Controller">
 226      Controller
 227    </a>
 228    <ul class="toc_section">
 229      <li><a href="#Controller-extend">extend</a></li>
 230      <li><a href="#Controller-routes">routes</a></li>
 231      <li><a href="#Controller-constructor">constructor / initialize</a></li>
 232      <li><a href="#Controller-route">route</a></li>
 233      <li><a href="#Controller-saveLocation">saveLocation</a></li>
 234    </ul>
 235
 236    <a class="toc_title" href="#History">
 237      History
 238    </a>
 239    <ul class="toc_section">
 240      <li><a href="#History-start">start</a></li>
 241    </ul>
 242
 243    <a class="toc_title" href="#Sync">
 244      Sync
 245    </a>
 246    <ul class="toc_section">
 247      <li><a href="#Sync">Backbone.sync</a></li>
 248      <li><a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
 249      <li><a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
 250    </ul>
 251
 252    <a class="toc_title" href="#View">
 253      View
 254    </a>
 255    <ul class="toc_section">
 256      <li><a href="#View-extend">extend</a></li>
 257      <li><a href="#View-constructor">constructor / initialize</a></li>
 258      <li><a href="#View-el">el</a></li>
 259      <li><a href="#View-dollar">$ (jQuery or Zepto)</a></li>
 260      <li><a href="#View-render">render</a></li>
 261      <li><a href="#View-remove">remove</a></li>
 262      <li><a href="#View-make">make</a></li>
 263      <li><a href="#View-delegateEvents">delegateEvents</a></li>
 264    </ul>
 265
 266    <a class="toc_title" href="#examples">
 267      Examples
 268    </a>
 269
 270    <a class="toc_title" href="#faq">
 271      F.A.Q.
 272    </a>
 273    <ul class="toc_section">
 274      <li><a href="#FAQ-events">Catalog of Events</a></li>
 275      <li><a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
 276      <li><a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
 277      <li><a href="#FAQ-mvc">Traditional MVC</a></li>
 278      <li><a href="#FAQ-this">Binding "this"</a></li>
 279      <li>- <a href="#FAQ-rias">Other RIA Frameworks</a></li>
 280    </ul>
 281
 282    <a class="toc_title" href="#changelog">
 283      Change Log
 284    </a>
 285
 286  </div>
 287
 288  <div class="container">
 289
 290    <p>
 291      <img style="width: 385px; height: 126px;" src="docs/images/backbone.png" alt="Backbone.js" />
 292    </p>
 293
 294    <p>
 295      <a href="http://github.com/documentcloud/backbone/">Backbone</a>
 296      supplies structure to JavaScript-heavy applications by providing <b>models</b> with
 297      key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
 298      <b>views</b> with declarative event handling, and connects it all to your
 299      existing application over a RESTful JSON interface.
 300    </p>
 301
 302    <p>
 303      The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
 304      and the <a href="docs/backbone.html">annotated source code</a> is available,
 305      as well as an online <a href="test/test.html">test suite</a>, and
 306      <a href="examples/todos/index.html">example application</a>.
 307    </p>
 308
 309    <p>
 310      You can report bugs and discuss features on the
 311      <a href="http://github.com/documentcloud/backbone/issues">issues page</a>,
 312      on Freenode in the <tt>#documentcloud</tt> channel,
 313      or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
 314    </p>
 315
 316    <p>
 317      <i>
 318        Backbone is an open-source component of
 319        <a href="http://documentcloud.org/">DocumentCloud</a>.
 320      </i>
 321    </p>
 322
 323    <h2 id="downloads">
 324      Downloads &amp; Dependencies
 325      <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
 326    </h2>
 327
 328    <table>
 329      <tr>
 330        <td><a href="backbone.js">Development Version (0.3.3)</a></td>
 331        <td><i>35kb, Uncompressed with Comments</i></td>
 332      </tr>
 333      <tr>
 334        <td><a href="backbone-min.js">Production Version (0.3.3)</a></td>
 335        <td><i>3.9kb, Packed and Gzipped</i></td>
 336      </tr>
 337    </table>
 338
 339    <p>
 340      Backbone's only hard dependency is
 341      <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
 342      For RESTful persistence, and DOM manipulation with
 343      <a href="#View">Backbone.View</a>,
 344      it's highly recommended to include
 345      <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
 346      <a href="http://jquery.com">jQuery</a> or <a href="http://zeptojs.com/">Zepto</a>.
 347    </p>
 348
 349    <h2 id="Introduction">Introduction</h2>
 350
 351    <p>
 352      When working on a web application that involves a lot of JavaScript, one
 353      of the first things you learn is to stop tying your data to the DOM. It's all
 354      too easy to create JavaScript applications that end up as tangled piles of
 355      jQuery selectors and callbacks, all trying frantically to keep data in
 356      sync between the HTML UI, your JavaScript logic, and the database on your
 357      server. For rich client-side applications, a more structured approach
 358      is helpful.
 359    </p>
 360
 361    <p>
 362      With Backbone, you represent your data as
 363      <a href="#Model">Models</a>, which can be created, validated, destroyed,
 364      and saved to the server. Whenever a UI action causes an attribute of
 365      a model to change, the model triggers a <i>"change"</i> event; all
 366      the <a href="#View">Views</a> that display the model's data are notified of the
 367      event, causing them to re-render. You don't have to write the glue
 368      code that looks into the DOM to find an element with a specific <i>id</i>,
 369      and update the HTML manually
 370      &mdash; when the model changes, the views simply update themselves.
 371    </p>
 372
 373    <p>
 374      Many of the examples that follow are runnable. Click the <i>play</i> button
 375      to execute them.
 376    </p>
 377
 378    <h2 id="Events">Backbone.Events</h2>
 379
 380    <p>
 381      <b>Events</b> is a module that can be mixed in to any object, giving the
 382      object the ability to bind and trigger custom named events. Events do not
 383      have to be declared before they are bound, and may take passed arguments.
 384      For example:
 385    </p>
 386
 387<pre class="runnable">
 388var object = {};
 389
 390_.extend(object, Backbone.Events);
 391
 392object.bind("alert", function(msg) {
 393  alert("Triggered " + msg);
 394});
 395
 396object.trigger("alert", "an event");
 397</pre>
 398
 399    <p id="Events-bind">
 400      <b class="header">bind</b><code>object.bind(event, callback)</code>
 401      <br />
 402      Bind a <b>callback</b> function to an object. The callback will be invoked
 403      whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
 404      If you have a large number of different events on a page, the convention is to use colons to
 405      namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
 406    </p>
 407
 408    <p>
 409      Callbacks bound to the special
 410      <tt>"all"</tt> event will be triggered when any event occurs, and are passed
 411      the name of the event as the first argument. For example, to proxy all events
 412      from one object to another:
 413    </p>
 414
 415<pre>
 416proxy.bind("all", function(eventName) {
 417  object.trigger(eventName);
 418});
 419</pre>
 420
 421    <p id="Events-unbind">
 422      <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
 423      <br />
 424      Remove a previously-bound <b>callback</b> function from an object. If no
 425      callback is specified, all callbacks for the <b>event</b> will be
 426      removed. If no event is specified, <i>all</i> event callbacks on the object
 427      will be removed.
 428    </p>
 429
 430<pre>
 431object.unbind("change", onChange);  // Removes just the onChange callback.
 432
 433object.unbind("change");            // Removes all "change" callbacks.
 434
 435object.unbind();                    // Removes all callbacks on object.
 436</pre>
 437
 438    <p id="Events-trigger">
 439      <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
 440      <br />
 441      Trigger callbacks for the given <b>event</b>. Subsequent arguments to
 442      <b>trigger</b> will be passed along to the event callbacks.
 443    </p>
 444
 445    <h2 id="Model">Backbone.Model</h2>
 446
 447    <p>
 448      <b>Models</b> are the heart of any JavaScript application, containing
 449      the interactive data as well as a large part of the logic surrounding it:
 450      conversions, validations, computed properties, and access control. You
 451      extend <b>Backbone.Model</b> with your domain-specific methods, and
 452      <b>Model</b> provides a basic set of functionality for managing changes.
 453    </p>
 454
 455    <p>
 456      The following is a contrived example, but it demonstrates defining a model
 457      with a custom method, setting an attribute, and firing an event keyed
 458      to changes in that specific attribute.
 459      After running this code once, <tt>sidebar</tt> will be
 460      available in your browser's console, so you can play around with it.
 461    </p>
 462
 463<pre class="runnable">
 464var Sidebar = Backbone.Model.extend({
 465  promptColor: function() {
 466    var cssColor = prompt("Please enter a CSS color:");
 467    this.set({color: cssColor});
 468  }
 469});
 470
 471window.sidebar = new Sidebar;
 472
 473sidebar.bind('change:color', function(model, color) {
 474  $('#sidebar').css({background: color});
 475});
 476
 477sidebar.set({color: 'white'});
 478
 479sidebar.promptColor();
 480</pre>
 481
 482    <p id="Model-extend">
 483      <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
 484      <br />
 485      To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
 486      and provide instance <b>properties</b>, as well as optional
 487      <b>classProperties</b> to be attached directly to the constructor function.
 488    </p>
 489
 490    <p>
 491      <b>extend</b> correctly sets up the prototype chain, so subclasses created
 492      with <b>extend</b> can be further extended and subclassed as far as you like.
 493    </p>
 494
 495<pre>
 496var Note = Backbone.Model.extend({
 497
 498  initialize: function() { ... },
 499
 500  author: function() { ... },
 501
 502  allowedToEdit: function(account) { ... },
 503
 504  coordinates: function() { ... }
 505
 506});
 507</pre>
 508
 509    <p class="warning">
 510        Brief aside on <tt>super</tt>: JavaScript does not provide
 511        a simple way to call super &mdash; the function of the same name defined
 512        higher on the prototype chain. If you override a core function like
 513        <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
 514        parent object's implementation, you'll have to explicitly call it, along these lines:
 515    </p>
 516
 517<pre>
 518var Note = Backbone.Model.extend({
 519  set: function(attributes, options) {
 520    Backbone.Model.prototype.set.call(this, attributes, options);
 521    ...
 522  }
 523});
 524</pre>
 525
 526    <p id="Model-constructor">
 527      <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
 528      <br />
 529      When creating an instance of a model, you can pass in the initial values
 530      of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
 531      model. If you define an <b>initialize</b> function, it will be invoked when
 532      the model is created.
 533    </p>
 534
 535<pre>
 536new Book({
 537  title: "One Thousand and One Nights",
 538  author: "Scheherazade"
 539});
 540</pre>
 541
 542    <p id="Model-get">
 543      <b class="header">get</b><code>model.get(attribute)</code>
 544      <br />
 545      Get the current value of an attribute from the model. For example:
 546      <tt>note.get("title")</tt>
 547    </p>
 548
 549    <p id="Model-escape">
 550      <b class="header">escape</b><code>model.escape(attribute)</code>
 551      <br />
 552      Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
 553      of a model's attribute. If you're interpolating data from the model into
 554      HTML, using <b>escape</b> to retrieve attributes will prevent
 555      <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
 556    </p>
 557
 558<pre class="runnable">
 559var hacker = new Backbone.Model({
 560  name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
 561});
 562
 563alert(hacker.escape('name'));
 564</pre>
 565
 566    <p id="Model-set">
 567      <b class="header">set</b><code>model.set(attributes, [options])</code>
 568      <br />
 569      Set a hash of attributes (one or many) on the model. If any of the attributes
 570      change the models state, a <tt>"change"</tt> event will be triggered, unless
 571      <tt>{silent: true}</tt> is passed as an option. Change events for specific
 572      attributes are also triggered, and you can bind to those as well, for example:
 573      <tt>change:title</tt>, and <tt>change:content</tt>.
 574    </p>
 575
 576<pre>
 577note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
 578</pre>
 579
 580    <p>
 581      If the model has a <a href="#Model-validate">validate</a> method,
 582      it will be validated before the attributes are set, no changes will
 583      occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
 584      You may also pass an <tt>error</tt>
 585      callback in the options, which will be invoked instead of triggering an
 586      <tt>"error"</tt> event, should validation fail.
 587    </p>
 588
 589    <p id="Model-escape">
 590      <b class="header">escape</b><code>model.escape(attribute)</code>
 591      <br />
 592      Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
 593      of a model's attribute. If you're interpolating data from the model into
 594      HTML, using <b>escape</b> to retrieve attributes will prevent
 595      <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
 596    </p>
 597
 598<pre class="runnable">
 599var hacker = new Backbone.Model({
 600  name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
 601});
 602
 603alert(hacker.escape('name'));
 604</pre>
 605
 606    <p id="Model-has">
 607      <b class="header">has</b><code>model.has(attribute)</code>
 608      <br />
 609      Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
 610      value.
 611    </p>
 612
 613<pre>
 614if (note.has("title")) {
 615  ...
 616}
 617</pre>
 618
 619    <p id="Model-unset">
 620      <b class="header">unset</b><code>model.unset(attribute, [options])</code>
 621      <br />
 622      Remove an attribute by deleting it from the internal attributes hash.
 623      Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
 624    </p>
 625
 626    <p id="Model-clear">
 627      <b class="header">clear</b><code>model.clear([options])</code>
 628      <br />
 629      Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
 630      <tt>silent</tt> is passed as an option.
 631    </p>
 632
 633    <p id="Model-id">
 634      <b class="header">id</b><code>model.id</code>
 635      <br />
 636      A special property of models, the <b>id</b> is an arbitrary string
 637      (integer id or UUID). If you set the <b>id</b> in the
 638      attributes hash, it will be copied onto the model as a direct property.
 639      Models can be retrieved by id from collections, and the id is used to generate
 640      model URLs by default.
 641    </p>
 642
 643    <p id="Model-cid">
 644      <b class="header">cid</b><code>model.cid</code>
 645      <br />
 646      A special property of models, the <b>cid</b> or client id is a unique identifier
 647      automatically assigned to all models when they're first created. Client ids
 648      are handy when the model has not yet been saved to the server, and does not
 649      yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
 650      Client ids take the form: <tt>c1, c2, c3 ...</tt>
 651    </p>
 652
 653    <p id="Model-attributes">
 654      <b class="header">attributes</b><code>model.attributes</code>
 655      <br />
 656      The <b>attributes</b> property is the internal hash containing the model's
 657      state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
 658      them directly. If you'd like to retrieve and munge a copy of the model's
 659      attributes, use <a href="#Model-toJSON">toJSON</a> instead.
 660    </p>
 661
 662    <p id="Model-defaults">
 663      <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
 664      <br />
 665      The <b>defaults</b> hash (or function) can be used to specify the default
 666      attributes for your model. When creating an instance of the model,
 667      any unspecified attributes will be set to their default value.
 668    </p>
 669
 670<pre class="runnable">
 671var Meal = Backbone.Model.extend({
 672  defaults: {
 673    "appetizer":  "caesar salad",
 674    "entree":     "ravioli",
 675    "dessert":    "cheesecake"
 676  }
 677});
 678
 679alert("Dessert will be " + (new Meal).get('dessert'));
 680</pre>
 681
 682    <p id="Model-toJSON">
 683      <b class="header">toJSON</b><code>model.toJSON()</code>
 684      <br />
 685      Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
 686      This can be used for persistence, serialization, or for augmentation before
 687      being handed off to a view. The name of this method is a bit confusing, as
 688      it doesn't actually return a JSON string &mdash; but I'm afraid that it's
 689      the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
 690    </p>
 691
 692<pre class="runnable">
 693var artist = new Backbone.Model({
 694  firstName: "Wassily",
 695  lastName: "Kandinsky"
 696});
 697
 698artist.set({birthday: "December 16, 1866"});
 699
 700alert(JSON.stringify(artist));
 701</pre>
 702
 703    <p id="Model-fetch">
 704      <b class="header">fetch</b><code>model.fetch([options])</code>
 705      <br />
 706      Refreshes the model's state from the server. Useful if the model has never
 707      been populated with data, or if you'd like to ensure that you have the
 708      latest server state. A <tt>"change"</tt> event will be triggered if the
 709      server's state differs from the current attributes. Accepts
 710      <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
 711      are passed <tt>(model, response)</tt> as arguments.
 712    </p>
 713
 714<pre>
 715// Poll every 10 seconds to keep the channel model up-to-date.
 716setInterval(function() {
 717  channel.fetch();
 718}, 10000);
 719</pre>
 720
 721    <p id="Model-save">
 722      <b class="header">save</b><code>model.save([attributes], [options])</code>
 723      <br />
 724      Save a model to your database (or alternative persistence layer),
 725      by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
 726      hash (as in <a href="#Model-set">set</a>) should contain the attributes
 727      you'd like to change -- keys that aren't mentioned won't be altered.
 728      If the model has a <a href="#Model-validate">validate</a>
 729      method, and validation fails, the model will not be saved. If the model
 730      <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
 731      (HTTP <tt>POST</tt>), if the model already
 732      exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
 733    </p>
 734
 735    <p>
 736      In the following example, notice how because the model has never been
 737      saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
 738    </p>
 739
 740<pre class="runnable">
 741Backbone.sync = function(method, model) {
 742  alert(method + ": " + JSON.stringify(model));
 743};
 744
 745var book = new Backbone.Model({
 746  title: "The Rough Riders",
 747  author: "Theodore Roosevelt"
 748});
 749
 750book.save();
 751</pre>
 752
 753    <p>
 754      <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
 755      options hash, which are passed <tt>(model, response)</tt> as arguments.
 756      The <tt>error</tt> callback will also be invoked if the model has a
 757      <tt>validate</tt> method, and validation fails. If a server-side
 758      validation fails, return a non-<tt>200</tt> HTTP response code, along with
 759      an error response in text or JSON.
 760    </p>
 761
 762<pre>
 763book.save({author: "F.D.R."}, {error: function(){ ... }});
 764</pre>
 765
 766    <p id="Model-destroy">
 767      <b class="header">destroy</b><code>model.destroy([options])</code>
 768      <br />
 769      Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
 770      request to <a href="#Sync">Backbone.sync</a>. Accepts
 771      <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
 772      Triggers a <tt>"destroy"</tt> event on the model, which will bubble up 
 773      through any collections that contain it.
 774    </p>
 775
 776<pre>
 777book.destroy({success: function(model, response) {
 778  ...
 779}});
 780</pre>
 781
 782    <p id="Model-validate">
 783      <b class="header">validate</b><code>model.validate(attributes)</code>
 784      <br />
 785      This method is left undefined, and you're encouraged to override it with
 786      your custom validation logic, if you have any that can be performed
 787      in JavaScript. <b>validate</b> is called before <tt>set</tt> and
 788      <tt>save</tt>, and is passed the attributes that are about to be updated.
 789      If the model and attributes are valid, don't return anything from <b>validate</b>;
 790      if the attributes are invalid, return an error of your choosing. It
 791      can be as simple as a string error message to be displayed, or a complete
 792      error object that describes the error programmatically. <tt>set</tt> and
 793      <tt>save</tt> will not continue if <b>validate</b> returns an error.
 794      Failed validations trigger an <tt>"error"</tt> event.
 795    </p>
 796
 797<pre class="runnable">
 798var Chapter = Backbone.Model.extend({
 799  validate: function(attrs) {
 800    if (attrs.end < attrs.start) {
 801      return "can't end before it starts";
 802    }
 803  }
 804});
 805
 806var one = new Chapter({
 807  title : "Chapter One: The Beginning"
 808});
 809
 810one.bind("error", function(model, error) {
 811  alert(model.get("title") + " " + error);
 812});
 813
 814one.set({
 815  start: 15,
 816  end:   10
 817});
 818</pre>
 819
 820    <p>
 821      <tt>"error"</tt> events are useful for providing coarse-grained error
 822      messages at the model or collection level, but if you have a specific view
 823      that can better handle the error, you may override and suppress the event
 824      by passing an <tt>error</tt> callback directly:
 825    </p>
 826
 827<pre>
 828account.set({access: "unlimited"}, {
 829  error: function(model, error) {
 830    alert(error);
 831  }
 832});
 833</pre>
 834
 835    <p id="Model-url">
 836      <b class="header">url</b><code>model.url()</code>
 837      <br />
 838      Returns the relative URL where the model's resource would be located on
 839      the server. If your models are located somewhere else, override this method
 840      with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
 841      falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
 842    </p>
 843
 844    <p>
 845      Delegates to <a href="#Collection-url">Collection#url</a> to generate the
 846      URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
 847      property, if all models of this class share a common root URL.
 848      A model with an id of <tt>101</tt>, stored in a
 849      <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
 850      would have this URL: <tt>"/documents/7/notes/101"</tt>
 851    </p>
 852
 853    <p id="Model-urlRoot">
 854      <b class="header">urlRoot</b><code>model.urlRoot</code>
 855      <br />
 856      Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
 857      to enable the default <a href="#Model-url">url</a> function to generate
 858      URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
 859    </p>
 860
 861<pre class="runnable">
 862var Book = Backbone.Model.extend({urlRoot : '/books'});
 863
 864var solaris = new Book({id: "1083-lem-solaris"});
 865
 866alert(solaris.url());
 867</pre>
 868
 869    <p id="Model-parse">
 870      <b class="header">parse</b><code>model.parse(response)</code>
 871      <br />
 872      <b>parse</b> is called whenever a model's data is returned by the
 873      server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
 874      The function is passed the raw <tt>response</tt> object, and should return
 875      the attributes hash to be <a href="#Model-set">set</a> on the model. The
 876      default implementation is a no-op, simply passing through the JSON response.
 877      Override this if you need to work with a preexisting API, or better namespace
 878      your responses.
 879    </p>
 880
 881    <p>
 882      If you're working with a Rails backend, you'll notice that Rails' default
 883      <tt>to_json</tt> implementation includes a model's attributes under a
 884      namespace. To disable this behavior for seamless Backbone integration, set:
 885    </p>
 886
 887<pre>
 888ActiveRecord::Base.include_root_in_json = false
 889</pre>
 890
 891    <p id="Model-clone">
 892      <b class="header">clone</b><code>model.clone()</code>
 893      <br />
 894      Returns a new instance of the model with identical attributes.
 895    </p>
 896
 897    <p id="Model-isNew">
 898      <b class="header">isNew</b><code>model.isNew()</code>
 899      <br />
 900      Has this model been saved to the server yet? If the model does not yet have
 901      an <tt>id</tt>, it is considered to be new.
 902    </p>
 903
 904    <p id="Model-change">
 905      <b class="header">change</b><code>model.change()</code>
 906      <br />
 907      Manually trigger the <tt>"change"</tt> event.
 908      If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
 909      aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
 910      when you're all finished.
 911    </p>
 912
 913    <p id="Model-hasChanged">
 914      <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
 915      <br />
 916      Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
 917      is passed, returns <tt>true</tt> if that specific attribute has changed.
 918    </p>
 919
 920<pre>
 921book.bind("change", function() {
 922  if (book.hasChanged("title")) {
 923    ...
 924  }
 925});
 926</pre>
 927
 928    <p id="Model-changedAttributes">
 929      <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
 930      <br />
 931      Retrieve a hash of only the model's attributes that have changed. Optionally,
 932      an external <b>attributes</b> hash can be passed in, returning
 933      the attributes in that hash which differ from the model. This can be used
 934      to figure out which portions of a view should be updated, or what calls
 935      need to be made to sync the changes to the server.
 936    </p>
 937
 938    <p id="Model-previous">
 939      <b class="header">previous</b><code>model.previous(attribute)</code>
 940      <br />
 941      During a <tt>"change"</tt> event, this method can be used to get the
 942      previous value of a changed attribute.
 943    </p>
 944
 945<pre class="runnable">
 946var bill = new Backbone.Model({
 947  name: "Bill Smith"
 948});
 949
 950bill.bind("change:name", function(model, name) {
 951  alert("Changed name from " + bill.previous("name") + " to " + name);
 952});
 953
 954bill.set({name : "Bill Jones"});
 955</pre>
 956
 957    <p id="Model-previousAttributes">
 958      <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
 959      <br />
 960      Return a copy of the model's previous attributes. Useful for getting a
 961      diff between versions of a model, or getting back to a valid state after
 962      an error occurs.
 963    </p>
 964
 965    <h2 id="Collection">Backbone.Collection</h2>
 966
 967    <p>
 968      Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
 969      to be notified when any model in the collection has been modified,
 970      listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
 971      the collection from the server, and use a full suite of
 972      <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
 973    </p>
 974
 975    <p>
 976      Any event that is triggered on a model in a collection will also be
 977      triggered on the collection directly, for convenience.
 978      This allows you to listen for changes to specific attributes in any
 979      model in a collection, for example:
 980      <tt>Documents.bind("change:selected", ...)</tt>
 981    </p>
 982
 983    <p id="Collection-extend">
 984      <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
 985      <br />
 986      To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
 987      providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
 988      directly to the collection's constructor function.
 989    </p>
 990
 991    <p id="Collection-model">
 992      <b class="header">model</b><code>collection.model</code>
 993      <br />
 994      Override this property to specify the model class that the collection
 995      contains. If defined, you can pass raw attributes objects (and arrays) to
 996      <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
 997      and <a href="#Collection-refresh">refresh</a>, and the attributes will be
 998      converted into a model of the proper type.
 999    </p>
1000
1001<pre>
1002var Library = Backbone.Collection.extend({
1003  model: Book
1004});
1005</pre>
1006
1007    <p id="Collection-constructor">
1008      <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
1009      <br />
1010      When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
1011      The collection's <a href="#Collection-comparator">comparator</a> function
1012      may be included as an option. If you define an <b>initialize</b> function, it will be
1013      invoked when the collection is created.
1014    </p>
1015
1016<pre>
1017var tabs = new TabSet([tab1, tab2, tab3]);
1018</pre>
1019
1020    <p id="Collection-models">
1021      <b class="header">models</b><code>collection.models</code>
1022      <br />
1023      Raw access to the JavaScript array of models inside of the collection. Usually you'll
1024      want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
1025      to access model objects, but occasionally a direct reference to the array
1026      is desired.
1027    </p>
1028
1029    <p id="Collection-toJSON">
1030      <b class="header">toJSON</b><code>collection.toJSON()</code>
1031      <br />
1032      Return an array containing the attributes hash of each model in the
1033      collection. This can be used to serialize and persist the
1034      collection as a whole. The name of this method is a bit confusing, because
1035      it conforms to
1036      <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
1037    </p>
1038
1039<pre class="runnable">
1040var collection = new Backbone.Collection([
1041  {name: "Tim", age: 5},
1042  {name: "Ida", age: 26},
1043  {name: "Rob", age: 55}
1044]);
1045
1046alert(JSON.stringify(collection));
1047</pre>
1048
1049    <p id="Collection-Underscore-Methods">
1050      <b class="header">Underscore Methods (25)</b>
1051      <br />
1052      Backbone proxies to <b>Underscore.js</b> to provide 25 iteration functions
1053      on <b>Backbone.Collection</b>. They aren't all documented here, but
1054      you can take a look at the Underscore documentation for the full details&hellip;
1055    </p>
1056
1057    <ul>
1058      <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
1059      <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
1060      <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
1061      <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
1062      <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
1063      <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
1064      <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
1065      <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
1066      <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
1067      <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
1068      <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
1069      <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
1070      <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
1071      <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
1072      <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
1073      <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
1074      <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
1075      <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
1076      <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
1077      <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
1078      <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
1079      <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
1080      <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
1081      <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
1082      <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
1083    </ul>
1084
1085<pre>
1086Books.each(function(book) {
1087  book.publish();
1088});
1089
1090var titles = Books.map(function(book) {
1091  return book.get("title");
1092});
1093
1094var publishedBooks = Books.filter(function(book) {
1095  return book.get("published") === true;
1096});
1097
1098var alphabetical = Books.sortBy(function(book) {
1099  return book.author.get("name").toLowerCase();
1100});
1101</pre>
1102
1103    <p id="Collection-add">
1104      <b class="header">add</b><code>collection.add(models, [options])</code>
1105      <br />
1106      Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
1107      event, which you can pass <tt>{silent: true}</tt> to suppress. If a
1108      <a href="#Collection-model">model</a> property is defined, you may also pass
1109      raw attributes objects.
1110    </p>
1111
1112<pre class="runnable">
1113var ships = new Backbone.Collection;
1114
1115ships.bind("add", function(ship) {
1116  alert("Ahoy " + ship.get("name") + "!");
1117});
1118
1119ships.add([
1120  {name: "Flying Dutchman"},
1121  {name: "Black Pearl"}
1122]);
1123</pre>
1124
1125    <p id="Collection-remove">
1126      <b class="header">remove</b><code>collection.remove(models, [options])</code>
1127      <br />
1128      Remove a model (or an array of models) from the collection. Fires a
1129      <tt>"remove"</tt> event, which you can use <tt>silent</tt>
1130      to suppress.
1131    </p>
1132
1133    <p id="Collection-get">
1134      <b class="header">get</b><code>collection.get(id)</code>
1135      <br />
1136      Get a model from a collection, specified by <b>id</b>.
1137    </p>
1138
1139<pre>
1140var book = Library.get(110);
1141</pre>
1142
1143    <p id="Collection-getByCid">
1144      <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
1145      <br />
1146      Get a model from a collection, specified by client id. The client id
1147      is the <tt>.cid</tt> property of the model, automatically assigned whenever
1148      a model is created. Useful for models which have not yet been saved to
1149      the server, and do not yet have true ids.
1150    </p>
1151
1152    <p id="Collection-at">
1153      <b class="header">at</b><code>collection.at(index)</code>
1154      <br />
1155      Get a model from a collection, specified by index. Useful if your collection
1156      is sorted, and if your collection isn't sorted, <b>at</b> will still
1157      retrieve models in insertion order.
1158    </p>
1159
1160    <p id="Collection-length">
1161      <b class="header">length</b><code>collection.length</code>
1162      <br />
1163      Like an array, a Collection maintains a <tt>length</tt> property, counting
1164      the number of models it contains.
1165    </p>
1166
1167    <p id="Collection-comparator">
1168      <b class="header">comparator</b><code>collection.comparator</code>
1169      <br />
1170      By default there is no <b>comparator</b> function on a collection.
1171      If you define a comparator, it will be used to maintain
1172      the collection in sorted order. This means that as models are added,
1173      they are inserted at the correct index in <tt>collection.models</tt>.
1174      Comparator functions take a model and return a numeric or string value
1175      by which the model should be ordered relative to others.
1176    </p>
1177
1178    <p>
1179      Note how even though all of the chapters in this example are added backwards,
1180      they come out in the proper order:
1181    </p>
1182
1183<pre class="runnable">
1184var Chapter  = Backbone.Model;
1185var chapters = new Backbone.Collection;
1186
1187chapters.comparator = function(chapter) {
1188  return chapter.get("page");
1189};
1190
1191chapters.add(new Chapter({page: 9, title: "The End"}));
1192chapters.add(new Chapter({page: 5, title: "The Middle"}));
1193chapters.add(new Chapter({page: 1, title: "The Beginning"}));
1194
1195alert(chapters.pluck('title'));
1196</pre>
1197
1198    <p class="warning">
1199      Brief aside: This comparator function is different than JavaScript's regular
1200      "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
1201      and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
1202    </p>
1203
1204    <p id="Collection-sort">
1205      <b class="header">sort</b><code>collection.sort([options])</code>
1206      <br />
1207      Force a collection to re-sort itself. You don't need to call this under
1208      normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
1209      will maintain itself in proper sort order at all times. Calling <b>sort</b>
1210      triggers the collection's <tt>"refresh"</tt> event, unless silenced by passing
1211      <tt>{silent: true}</tt>
1212    </p>
1213
1214    <p id="Collection-pluck">
1215      <b class="header">pluck</b><code>collection.pluck(attribute)</code>
1216      <br />
1217      Pluck an attribute from each model in the collection. Equivalent to calling
1218      <tt>map</tt>, and returning a single attribute from the iterator.
1219    </p>
1220
1221<pre class="runnable">
1222var stooges = new Backbone.Collection([
1223  new Backbone.Model({name: "Curly"}),
1224  new Backbone.Model({name: "Larry"}),
1225  new Backbone.Model({name: "Moe"})
1226]);
1227
1228var names = stooges.pluck("name");
1229
1230alert(JSON.stringify(names));
1231</pre>
1232
1233    <p id="Collection-url">
1234      <b class="header">url</b><code>collection.url or collection.url()</code>
1235      <br />
1236      Set the <b>url</b> property (or function) on a collection to reference
1237      its location on the server. Models within the collection will use <b>url</b>
1238      to construct URLs of their own.
1239    </p>
1240
1241<pre>
1242var Notes = Backbone.Collection.extend({
1243  url: '/notes'
1244});
1245
1246// Or, something more sophisticated:
1247
1248var Notes = Backbone.Collection.extend({
1249  url: function() {
1250    return this.document.url() + '/notes';
1251  }
1252});
1253</pre>
1254
1255    <p id="Collection-parse">
1256      <b class="header">parse</b><code>collection.parse(response)</code>
1257      <br />
1258      <b>parse</b> is called by Backbone whenever a collection's models are
1259      returned by the server, in <a href="#Collection-fetch">fetch</a>.
1260      The function is passed the raw <tt>response</tt> object, and should return
1261      the array of model attributes to be <a href="#Collection-add">added</a>
1262      to the collection. The default implementation is a no-op, simply passing
1263      through the JSON response. Override this if you need to work with a
1264      preexisting API, or better namespace your responses.
1265    </p>
1266
1267<pre>
1268var Tweets = Backbone.Collection.extend({
1269  // The Twitter Search API returns tweets under "results".
1270  parse: function(response) {
1271    return response.results;
1272  }
1273});
1274</pre>
1275
1276    <p id="Collection-fetch">
1277      <b class="header">fetch</b><code>collection.fetch([options])</code>
1278      <br />
1279      Fetch the default set of models for this collection from the server,
1280      refreshing the collection when they arrive. The <b>options</b> hash takes
1281      <tt>success</tt> and <tt>error</tt>
1282      callbacks which will be passed <tt>(collection, response)</tt> as arguments.
1283      When the model data returns from the server, the collection will
1284      <a href="#Collection-refresh">refresh</a>.
1285      Delegates to <a href="#Sync">Backbone.sync</a>
1286      under the covers, for custom persistence strategies.
1287      The server handler for <b>fetch</b> requests should return a JSON array of
1288      models.
1289    </p>
1290
1291<pre class="runnable">
1292Backbone.sync = function(method, model) {
1293  alert(method + ": " + model.url);
1294};
1295
1296var Accounts = new Backbone.Collection;
1297Accounts.url = '/accounts';
1298
1299Accounts.fetch();
1300</pre>
1301
1302    <p>
1303      If you'd like to add the incoming models to the current collection, instead
1304      of replacing the collection's contents, pass <tt>{add: true}</tt> as an
1305      option to <b>fetch</b>.
1306    </p>
1307
1308    <p>
1309      Note that <b>fetch</b> should not be used to populate collections on
1310      page load &mdash; all models needed at load time should already be
1311      <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
1312      intended for lazily-loading models for interfaces that are not needed
1313      immediately: for example, documents with collections of notes that may be
1314      toggled open and closed.
1315    </p>
1316
1317    <p id="Collection-refresh">
1318      <b class="header">refresh</b><code>collection.refresh(models, [options])</code>
1319      <br />
1320      Adding and removing models one at a time is all well and good, but sometimes
1321      you have so many models to change that you'd rather just update the collection
1322      in bulk. Use <b>refresh</b> to replace a collection with a new list
1323      of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
1324      at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
1325    </p>
1326
1327    <p>
1328      Here's an example using <b>refresh</b> to bootstrap a collection during initial page load,
1329      in a Rails application.
1330    </p>
1331
1332<pre>
1333&lt;script&gt;
1334  Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
1335&lt;/script&gt;
1336</pre>
1337
1338    <p id="Collection-create">
1339      <b class="header">create</b><code>collection.create(attributes, [options])</code>
1340      <br />
1341      Convenience to create a new instance of a model within a collection.
1342      Equivalent to instantiating a model with a hash of attributes,
1343      saving the model to the server, and adding the model to the set after being
1344      successfully created. Returns
1345      the model, or <tt>false</tt> if a validation error prevented the
1346      model from being created. In order for this to work, your should set the
1347      <a href="#Collection-model">model</a> property of the collection.
1348    </p>
1349
1350<pre>
1351var Library = Backbone.Collection.extend({
1352  model: Book
1353});
1354
1355var NYPL = new Library;
1356
1357var othello = NYPL.create({
1358  title: "Othello",
1359  author: "William Shakespeare"
1360});
1361</pre>
1362
1363    <h2 id="Controller">Backbone.Controller</h2>
1364
1365    <p>
1366      Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
1367      in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
1368      <b>Backbone.Controller</b> provides methods for routing client-side URL
1369      fragments, and connecting them to actions and events.
1370    </p>
1371
1372    <p class="warning">
1373      Backbone controllers do not yet make use of HTML5 <b>pushState</b> and
1374      <b>replaceState</b>. Currently, <b>pushState</b> and <b>replaceState</b>
1375      need special handling on the server-side, cause you to mint duplicate URLs,
1376      and have an incomplete API. We may start supporting them in the future
1377      when these issues have been resolved.
1378    </p>
1379
1380    <p>
1381      During page load, after your application has finished creating all of its controllers,
1382      be sure to call <tt>Backbone.history.start()</tt> to route the initial URL.
1383    </p>
1384
1385    <p id="Controller-extend">
1386      <b class="header">extend</b><code>Backbone.Controller.extend(properties, [classProperties])</code>
1387      <br />
1388      Get started by creating a custom controller class. You'll
1389      want to define actions that are triggered when certain URL fragments are
1390      matched, and provide a <a href="#Controller-routes">routes</a> hash
1391      that pairs routes to actions.
1392    </p>
1393
1394<pre>
1395var Workspace = Backbone.Controller.extend({
1396
1397  routes: {
1398    "help":                 "help",    // #help
1399    "search/:query":        "search",  // #search/kiwis
1400    "search/:query/p:page": "search"   // #search/kiwis/p7
1401  },
1402
1403  help: function() {
1404    ...
1405  },
1406
1407  search: function(query, page) {
1408    ...
1409  }
1410
1411});
1412</pre>
1413
1414    <p id="Controller-routes">
1415      <b class="header">routes</b><code>controller.routes</code>
1416      <br />
1417      The routes hash maps URLs with parameters to functions on your controller,
1418      similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
1419      Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
1420      component between slashes; and splat parts <tt>*splat</tt>, which can match
1421      any number of URL components.
1422    </p>
1423
1424    <p>
1425      For example, a route of <tt>"search/:query/p:page"</tt> will match
1426      a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
1427      and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
1428      match <tt>#file/nested/folder/file.txt</tt>,
1429      passing <tt>"nested/folder/file.txt"</tt> to the action.
1430    </p>
1431
1432    <p>
1433      When the visitor presses the back button, or enters a URL, and a particular
1434      route is matched, the name of the action will be fired as an
1435      <a href="#Events">event</a>, so that other objects can listen to the controller,
1436      and be notified. In the following example, visiting <tt>#help/uploading</tt>
1437      will fire a <tt>route:help</tt> event from the controller.
1438    </p>
1439
1440<pre>
1441routes: {
1442  "help/:page":         "help",
1443  "download/*path":     "download",
1444  "folder/:name":       "openFolder",
1445  "folder/:name-:mode": "openFolder"
1446}
1447</pre>
1448
1449<pre>
1450controller.bind("route:help", function(page) {
1451  ...
1452});
1453</pre>
1454
1455    <p id="Controller-constructor">
1456      <b class="header">constructor / initialize</b><code>new Controller([options])</code>
1457      <br />
1458      When creating a new controller, you may pass its
1459      <a href="#Controller-routes">routes</a> hash directly as an option, if you
1460      choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
1461      function, if defined.
1462    </p>
1463
1464    <p id="Controller-route">
1465      <b class="header">route</b><code>controller.route(route, name, callback)</code>
1466      <br />
1467      Manually create a route for the controller, The <tt>route</tt> argument may
1468      be a <a href="#Controller-routes">routing string</a> or regular expression.
1469      Each matching capture from the route or regular expression will be passed as
1470      an argument to the callback. The <tt>name</tt> argument will be triggered as
1471      a <tt>"route:name"</tt> event whenever the route is matched.
1472    </p>
1473
1474<pre>
1475initialize: function(options) {
1476
1477  // Matches #page/10, passing "10"
1478  this.route("page/:number", "page", function(number){ ... });
1479
1480  // Matches /117-a/b/c/open, passing "117-a/b/c"
1481  this.route(/^(.*?)\/open$/, "open", function(id){ ... });
1482
1483}
1484</pre>
1485
1486    <p id="Controller-saveLocation">
1487      <b class="header">saveLocation</b><code>controller.saveLocation(fragment)</code>
1488      <br />
1489      Whenever you reach a point in your application that you'd like to save
1490      as a URL, call <b>saveLocation</b> in order to update the URL fragment
1491      without triggering a <tt>hashchange</tt> event. (If you would prefer to
1492      trigger the event and routing, you can just set the hash directly.)
1493    </p>
1494
1495<pre>
1496openPage: function(pageNumber) {
1497  this.document.pages.at(pageNumber).open();
1498  this.saveLocation("page/" + pageNumber);
1499}
1500</pre>
1501
1502    <h2 id="History">Backbone.history</h2>
1503
1504    <p>
1505      <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
1506      events, match the appropriate route, and trigger callbacks. You shouldn't
1507      ever have to create one of these yourself &mdash; you should use the reference
1508      to <tt>Backbone.history</tt> that will be created for you automatically if you make use
1509      of <a href="#Controller">Controllers</a> with <a href="#Controller-routes">routes</a>.
1510    </p>
1511
1512    <p id="History-start">
1513      <b class="header">start</b><code>Backbone.history.start()</code>
1514      <br />
1515      When all of your <a href="#Controller">Controllers</a> have been created,
1516      and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
1517      to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
1518    </p>
1519
1520<pre>
1521$(function(){
1522  new WorkspaceController();
1523  new HelpPaneController();
1524  Backbone.history.start();
1525});
1526</pre>
1527
1528    <h2 id="Sync">Backbone.sync</h2>
1529
1530    <p>
1531      <b>Backbone.sync</b> is the function the Backbone calls every time it
1532      attempts to read or save a model to the server. By default, it uses
1533      <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request. You can override
1534      it in order to use a different persistence strategy, such as WebSockets,
1535      XML transport, or Local Storage.
1536    </p>
1537
1538    <p>
1539      The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, success, error)</tt>
1540    </p>
1541
1542    <ul>
1543      <li><b>method</b> – the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
1544      <li><b>model</b> – the model to be saved (or collection to be read)</li>
1545      <li><b>success({model: ...})</b> – a callback that should be fired if the request works</li>
1546      <li><b>error({model: ...})</b> – a callback that should be fired if the request fails</li>
1547    </ul>
1548
1549    <p>
1550      With the default implementation, when <b>Backbone.sync</b> sends up a request to save
1551      a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
1552      with content-type <tt>application/json</tt>. When returning a JSON response,
1553      send down the attributes of the  model that have been changed by the server, and need
1554      to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
1555      (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
1556      of model attribute objects.
1557    </p>
1558
1559    <p>
1560      The default <b>sync</b> handler maps CRUD to REST like so:
1561    </p>
1562
1563    <ul>
1564      <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
1565      <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
1566      <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
1567      <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
1568    </ul>
1569
1570    <p>
1571      As an example, a Rails handler responding to an <tt>"update"</tt> call from
1572      <tt>Backbone</tt> might look like this: <i>(In real code, never use
1573      </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
1574      you allow to be changed.)</i>
1575    </p>
1576
1577<pre>
1578def update
1579  account = Account.find params[:id]
1580  account.update_attributes params
1581  render :json => account
1582end
1583</pre>
1584
1585    <p>
1586      One more tip for Rails integration is to disable the default namespacing for
1587      <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
1588    </p>
1589
1590    <p id="Sync-emulateHTTP">
1591      <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
1592      <br />
1593      If you want to work with a legacy web server that doesn't support Backbones's
1594      default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
1595      Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
1596      a HTTP <tt>POST</tt>, and pass them under the <tt>_method</tt> parameter. Setting this option
1597      will also set an <tt>X-HTTP-Method-Override</tt> header with the true method.
1598    </p>
1599
1600<pre>
1601Backbone.emulateHTTP = true;
1602
1603model.save();  // POST to "/collection/id", with "_method=PUT" + header.
1604</pre>
1605
1606    <p id="Sync-emulateJSON">
1607      <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
1608      <br />
1609      If you're working with a legacy web server that can't handle requests
1610      encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
1611      will cause the JSON to be serialized under a <tt>model</tt> parameter, and
1612      the request to be made with a <tt>application/x-www-form-urlencoded</tt>
1613      mime type, as if from an HTML form.
1614    </p>
1615
1616    <h2 id="View">Backbone.View</h2>
1617
1618    <p>
1619      Backbone views are almost more convention than they are code &mdash; they
1620      don't determine anything about your HTML or CSS for you, and can be used
1621      with any JavaScript templating library.
1622      The general idea is to organize your interface into logical views,
1623      backed by models, each of which can be updated independently when the
1624      model changes, without having to redraw the page. Instead of digging into
1625      a JSON object, looking up an element in the DOM, and updating the HTML by hand,
1626      you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
1627      event &mdash; and now everywhere that
1628      model data is displayed in the UI, it is always immediately up to date.
1629    </p>
1630
1631    <p id="View-extend">
1632      <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
1633      <br />
1634      Get started with views by creating a custom view class. You'll want to
1635      override the <a href="#View-render">render</a> function, specify your
1636      declarative <a href="#View-delegateEvents">events</a>, and perhaps the
1637      <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
1638      element.
1639    </p>
1640
1641<pre>
1642var DocumentRow = Backbone.View.extend({
1643
1644  tagName: "li",
1645
1646  className: "document-row",
1647
1648  events: {
1649    "click .icon":          "open",
1650    "click .button.edit":   "openEditDialog",
1651    "click .button.delete": "destroy"
1652  },
1653
1654  initialize: function() {
1655    _.bindAll(this, "render");
1656  },
1657
1658  render: function() {
1659    ...
1660  }
1661
1662});
1663</pre>
1664
1665    <p id="View-constructor">
1666      <b class="header">constructor / initialize</b><code>new View([options])</code>
1667      <br />
1668      When creating a new View, the options you pass are attached to the view
1669      as <tt>this.options</tt>, for future reference. There are several special
1670      options that, if passed, will be attached directly to the view:
1671      <tt>model</tt>, <tt>collection</tt>,
1672      <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, and <tt>tagName</tt>.
1673      If the view defines an <b>initialize</b> function, it will be called when
1674      the view is first created. If you'd like to create a view that references
1675      an element <i>already</i> in the DOM, pass in the element as an option:
1676      <tt>new View({el: existingElement})</tt>
1677    </p>
1678
1679<pre>
1680var doc = Documents.first();
1681
1682new DocumentRow({
1683  model: doc,
1684  id: "document-row-" + doc.id
1685});
1686</pre>
1687
1688    <p id="View-el">
1689      <b class="header">el</b><code>view.el</code>
1690      <br />
1691      All views have a DOM element at all times (the <b>el</b> property),
1692      whether they've already been inserted into the page or not. In this
1693      fashion, views can be rendered at any time, and inserted into the DOM all
1694      at once, in order to get high-performance UI rendering with as few
1695      reflows and repaints as possible. <tt>this.el</tt> is created from the
1696      view's <tt>tagName</tt>, <tt>className</tt>, and <tt>id</tt> properties,
1697      if specified. If not, <b>el</b> is an empty <tt>div</tt>.
1698    </p>
1699
1700    <p>
1701      You may assign <b>el</b> directly if the view is being
1702      created for an element that already exists in the DOM. Use either a
1703      reference to a real DOM element, or a css selector string.
1704    </p>
1705
1706<pre class="runnable">
1707var ItemView = Backbone.View.extend({
1708  tagName: 'li'
1709});
1710
1711var BodyView = Backbone.View.extend({
1712  el: 'body'
1713});
1714
1715var item = new ItemView();
1716var body = new BodyView();
1717
1718alert(item.el + ' ' + body.el);
1719</pre>
1720
1721    <p id="View-dollar">
1722      <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
1723      <br />
1724      If jQuery or Zepto is included on the page, each view has a
1725      <b>$</b> function that runs queries scoped within the view's element. If you use this
1726      scoped jQuery function, you don't have to use model ids as part of your query
1727      to pull out specific elements in a list, and can rely much more on HTML class
1728      attributes. It's equivalent to running: <tt>$(selector, this.el)</tt>
1729    </p>
1730
1731<pre>
1732ui.Chapter = Backbone.View.extend({
1733  serialize : function() {
1734    return {
1735      title: this.$(".title").text(),
1736      start: this.$(".start-page").text(),
1737      end:   this.$(".end-page").text()
1738    };
1739  }
1740});
1741</pre>
1742
1743    <p id="View-render">
1744      <b class="header">render</b><code>view.render()</code>
1745      <br />
1746      The default implementation of <b>render</b> is a no-op. Override this
1747      function with your code that renders the view template from model data,
1748      and updates <tt>this.el</tt> with the new HTML. A good
1749      convention is to <tt>return this</tt> at the end of <b>render</b> to
1750      enable chained calls.
1751    </p>
1752
1753<pre>
1754var Bookmark = Backbone.View.extend({
1755  render: function() {
1756    $(this.el).html(this.template(this.model.toJSON()));
1757    return this;
1758  }
1759});
1760</pre>
1761
1762    <p>
1763      Backbone is agnostic with respect to your preferred method of HTML templating.
1764      Your <b>render</b> function could even munge together an HTML string, or use
1765      <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
1766      choosing a nice JavaScript templating library.
1767      <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
1768      <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
1769      <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
1770      Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
1771      <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
1772      is available, and is an excellent choice if you've already XSS-sanitized
1773      your interpolated data.
1774    </p>
1775
1776    <p>
1777      Whatever templating strategy you end up with, it's nice if you <i>never</i>
1778      have to put strings of HTML in your JavaScript. At DocumentCloud, we
1779      use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
1780      to package up JavaScript templates stored in <tt>/app/views</tt> as part
1781      of our main <tt>core.js</tt> asset package.
1782    </p>
1783
1784    <p id="View-remove">
1785      <b class="header">remove</b><code>view.remove()</code>
1786      <br />
1787      Convenience function for removing the view from the DOM. Equivalent to calling
1788      <tt>$(view.el).remove();</tt>
1789    </p>
1790
1791    <p id="View-make">
1792      <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
1793      <br />
1794      Convenience function for creating a DOM element of the given type (<b>tagName</b>),
1795      with optional attributes and HTML content. Used internally to create the
1796      initial <tt>view.el</tt>.
1797    </p>
1798
1799<pre class="runnable">
1800var view = new Backbone.View;
1801
1802var el = view.make("b", {className: "bold"}, "Bold! ");
1803
1804$("#make-demo").append(el);
1805</pre>
1806
1807<div id="make-demo"></div>
1808
1809    <p id="View-delegateEvents">
1810      <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
1811      <br />
1812      Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
1813      for DOM events within a view.
1814      If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
1815      as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
1816      Omitting the <tt>selector</tt> causes the event to be bound to the view's
1817      root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
1818      within the View's constructor for you, so if you have a simple <tt>events</tt>
1819      hash, all of your DOM events will always already be connected, and you will
1820      never have to call this function yourself.
1821    </p>
1822
1823    <p>
1824      Using <b>delegateEvents</b> provides a number of advantages over manually
1825      using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
1826      callbacks are bound to the view before being handed off to jQuery, so when
1827      the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
1828      <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
1829      hash, all callbacks are removed and delegated afresh &mdash; useful for
1830      views which need to behave differently when in different modes.
1831    </p>
1832
1833    <p>
1834      A view that displays a document in a search result might look
1835      something like this:
1836    </p>
1837
1838<pre>
1839var DocumentView = Backbone.View.extend({
1840
1841  events: {
1842    "dblclick"                : "open",
1843    "click .icon.doc"         : "select",
1844    "contextmenu .icon.doc"   : "showMenu",
1845    "click .show_notes"       : "toggleNotes",
1846    "click .title .lock"      : "editAccessLevel",
1847    "mouseover .title .date"  : "showTooltip"
1848  },
1849
1850  render: function() {
1851    $(this.el).html(this.template(this.model.toJSON()));
1852    return this;
1853  },
1854
1855  open: function() {
1856    window.open(this.model.get("viewer_url"));
1857  },
1858
1859  select: function() {
1860    this.model.set({selected: true});
1861  },
1862
1863  ...
1864
1865});
1866</pre>
1867
1868    <h2 id="examples">Examples</h2>
1869
1870    <p>
1871      <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
1872      <a href="examples/todos/index.html">Todo List application</a>
1873      that is bundled in the repository as Backbone example. If you're wondering
1874      where to get started with Backbone in general, take a moment to
1875      <a href="docs/todos.html">read through the annotated source</a>. The app uses a
1876      <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
1877      to transparently save all of your todos within your browser, instead of
1878      sending them to a server. Jérôme also has a version hosted at
1879      <a href="http://localtodos.com/">localtodos.com</a> that uses a
1880      <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
1881      instead of jQuery.
1882    </p>
1883
1884    <div style="text-align: center;">
1885      <a href="examples/todos/index.html">
1886        <img src="docs/images/todos.png" alt="Todos" class="example_image" />
1887      </a>
1888    </div>
1889
1890    <p>
1891      The <a href="http://www.documentcloud.org/">DocumentCloud</a> workspace
1892      is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
1893      <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
1894    </p>
1895
1896    <div style="text-align: center;">
1897      <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" class="example_image" />
1898    </div>
1899
1900    <p>
1901      <a href="http://bennolan.com/">Ben Nolan</a> created
1902      <a href="http://bennolan.com/2010/11/24/backbone-jquery-demo.html">an example "Backbone Mobile" application</a>, combining Backbone.js
1903      with <a href="http://jquerymobile.com/">jQuery Mobile</a>. You can
1904      <a href="http://bennolan.com/science/backbone-mobile/">try the app</a>
1905      in your browser, or view the
1906      <a href="https://github.com/bnolan/backbone-mobile">source code</a> on Github.
1907    </p>
1908
1909    <div style="text-align: center;">
1910      <a href="http://bennolan.com/science/backbone-mobile/">
1911        <img src="docs/images/backbone-mobile.png" alt="Backbone Mobile" class="example_image" />
1912      </a>
1913    </div>
1914    
1915    <p>
1916      <a href="http://twitter.com/evilchelu">Cristi Balan</a> and 
1917      <a href="http://dira.ro">Irina Dumitrascu</a> created 
1918      <a href="http://tzigla.com">Tzigla</a>, a collaborative drawing 
1919      application where artists make tiles that connect to each other to 
1920      create <a href="http://tzigla.com/boards/1">surreal drawings</a>.
1921      Backbone models help organize the code, controllers provide 
1922      <a href="http://tzigla.com/boards/1#!/tiles/2-2">bookmarkable deep links</a>, 
1923      and the views are rendered with 
1924      <a href="https://github.com/creationix/haml-js">haml.js</a> and 
1925      <a href="http://zeptojs.com/">Zepto</a>.
1926      Tzigla is written in Ruby (Rails) on the backend, and 
1927      <a href="http://coffeescript.org">CoffeeScript</a> on the frontend, with
1928      <a href="http://documentcloud.github.com/jammit/">Jammit</a> 
1929      prepackaging the static assets.
1930    </p>
1931    
1932    <div style="text-align: center;">
1933      <a href="http://www.tzigla.com/">
1934        <img src="docs/images/tzigla.png" alt="Tzigla" class="example_image" />
1935      </a>
1936    </div>
1937    
1938    <p>
1939      <a href="http://www.twitter.com/jamesjyu">James Yu</a> used Backbone.js to
1940      create <a href="http://www.quietwrite.com/">QuietWrite</a>, an app
1941      that gives writers a clean and quiet interface to concentrate on the text itself.
1942      It also works great on the iPad. The editor relies on
1943      Backbone to persist document data to the server.
1944    </p>
1945    
1946    <div style="text-align: center;">
1947      <a href="http://www.quietwrite.com/">
1948        <img src="docs/images/quietwrite.png" alt="QuietWrite" class="example_image" />
1949      </a>
1950    </div>
1951
1952    <h2 id="faq">F.A.Q.</h2>
1953
1954    <p id="FAQ-events">
1955      <b class="header">Catalog of Events</b>
1956      <br />
1957      Here's a list of all of the built-in events that Backbone.js can fire.
1958      You're also free to trigger your own events on Models and Views as you
1959      see fit.
1960    </p>
1961
1962    <ul>
1963      <li><b>"add"</b> (model, collection) &mdash; when a model is added to a collection. </li>
1964      <li><b>"remove"</b> (model, collection) &mdash; when a model is removed from a collection. </li>
1965      <li><b>"refresh"</b> (collection) &mdash; when the collection's entire contents have been replaced. </li>
1966      <li><b>"change"</b> (model, collection) &mdash; when a model's attributes have changed. </li>
1967      <li><b>"change:[attribute]"</b> (model, collection) &mdash; when a specific attribute has been updated. </li>
1968      <li><b>"destrooy"</b> (model, collection) &mdash; when a model is <a href="#Model-destroy">destroyed</a>. </li>
1969      <li><b>"error"</b> (model, collection) &mdash; when a model's validation fails, or a <a href="#Model-save">save</a> call fails on the server. </li>
1970      <li><b>"route:[name]"</b> (controller) &mdash; when one of a controller's routes has matched. </li>
1971      <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
1972    </ul>
1973
1974    <p id="FAQ-nested">
1975      <b class="header">Nested Models &amp; Collections</b>
1976      <br />
1977      It's common to nest collections inside of models with Backbone. For example,
1978      consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
1979      One nice pattern for handling this is have a <tt>this.messages</tt> collection
1980      for each mailbox, enabling the lazy-loading of messages, when the mailbox
1981      is first opened ... perhaps with <tt>MessageList</tt> views listening for
1982      <tt>"add"</tt> and <tt>"remove"</tt> events.
1983    </p>
1984
1985<pre>
1986var Mailbox = Backbone.Model.extend({
1987
1988  initialize: function() {
1989    this.messages = new Messages;
1990    this.messages.url = '/mailbox/' + this.id + '/messages';
1991    this.messages.bind("refresh", this.updateCounts);
1992  },
1993
1994  ...
1995
1996});
1997
1998var Inbox = new Mailbox;
1999
2000// And then, when the Inbox is opened:
2001
2002Inbox.messages.fetch();
2003</pre>
2004
2005    <p id="FAQ-bootstrap">
2006      <b class="header">Loading Bootstrapped Models</b>
2007      <br />
2008      When your app first loads, it's common to have a set of initial models that
2009      you know you're going to need, in order to render the page. Instead of
2010      firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
2011      a nicer pattern is to have their data already bootstrapped into the page.
2012      You can then use <a href="#Collection-refresh">refresh</a> to populate your
2013      collections with the initial data. At DocumentCloud, in the
2014      <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
2015      workspace, we do something along these lines:
2016    </p>
2017
2018<pre>
2019&lt;script&gt;
2020  Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
2021  Projects.refresh(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
2022&lt;/script&gt;
2023</pre>
2024
2025    <p id="FAQ-mvc">
2026      <b class="header">How does Backbone relate to "traditional" MVC?</b>
2027      <br />
2028      Different implementations of the
2029      <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
2030      pattern tend to disagree about the definition of a controller. If it helps any, in
2031      Backbone, the <a href="#View">View</a> class can also be thought of as a
2032      kind of controller, dispatching events that originate from the UI, with
2033      the HTML template serving as the true view. We call it a View because it
2034      represents a logical chunk of UI, responsible for the contents of a single
2035      DOM element.
2036    </p>
2037
2038    <p id="FAQ-this">
2039      <b class="header">Binding "this"</b>
2040      <br />
2041      Perhaps the single most common JavaScript "gotcha" is the fact that when
2042      you pass a function as a callback, it's value for <tt>this</tt> is lost. With
2043      Backbone, when dealing with <a href="#Events">events</a> and callbacks,
2044      you'll often find it useful to rely on
2045      <a href="http://documentcloud.github.com/underscore/#bind">_.bind</a> and
2046      <a href="http://documentcloud.github.com/underscore/#bindAll">_.bindAll</a>
2047      from Underscore.js. <tt>_.bind</tt> takes a function and an object to be
2048      used as <tt>this</tt>, any time the function is called in the future.
2049      <tt>_.bindAll</tt> takes an object and a list of method names: each method
2050      in the list will be bound to the object, so that it's <tt>this</tt> may
2051      not change. For example, in a <a href="#View">View</a> that listens for
2052      changes to a collection...
2053    </p>
2054
2055<pre>
2056var MessageList = Backbone.View.extend({
2057
2058  initialize: function() {
2059    _.bindAll(this, "addMessage", "removeMessage", "render");
2060
2061    var messages = this.collection;
2062    messages.bind("refresh", this.render);
2063    messages.bind("add", this.addMessage);
2064    messages.bind("remove", this.removeMessage);
2065  }
2066
2067});
2068
2069// Later, in the app...
2070
2071Inbox.messages.add(newMessage);
2072</pre>
2073
2074    <p id="FAQ-rias">
2075      <b class="header">
2076        How is Backbone different than
2077        <a href="http://www.sproutcore.com/">SproutCore</a> or
2078        <a href="http://cappuccino.org/">Cappuccino</a>?
2079      </b>
2080      <br />
2081      This question is frequently asked, and all three projects apply general
2082      <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
2083      principles to JavaScript applications. However, there isn't much basis
2084      for comparison. SproutCore and Cappuccino provide rich UI widgets, vast
2085      core libraries, and determine the structure of your HTML for you.
2086      Both frameworks measure in the hundreds of kilobytes when packed and
2087      gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser
2088      &mdash; there's a lot of room underneath for libraries of a more moderate scope.
2089      Backbone is a <i>4 kilobyte</i> include that provides
2090      just the core concepts of models, events, collections, views, controllers,
2091      and persistence.
2092    </p>
2093
2094    <h2 id="changelog">Change Log</h2>
2095
2096    <p>
2097      <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
2098      Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
2099      jQuery, as a framework for DOM manipulation and Ajax support.
2100      Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
2101      attributes intended for HTML interpolation. When trying to persist a model,
2102      failed requests will now trigger an <tt>"error"</tt> event. The
2103      ubiquitous <tt>options</tt> argument is now passed as the final argument
2104      to all <tt>"change"</tt> events.
2105    </p>
2106
2107    <p>
2108      <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
2109      Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
2110      overridden on a per-model, or per-collection basis. Fixed recursion error
2111      when calling <tt>save</tt> with no changed attributes, within a
2112      <tt>"change"</tt> event.
2113    </p>
2114
2115    <p>
2116      <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
2117      All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
2118      model, so that views can listen for them without having to know about the
2119      collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
2120      <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
2121      Backbone routes are now able to load empty URL fragments.
2122    </p>
2123
2124    <p>
2125      <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
2126      Backbone now has <a href="#Controller">Controllers</a> and
2127      <a href="#History">History</a>, for doing client-side routing based on
2128      URL fragments.
2129      Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
2130      do <tt>PUT</tt> and <tt>DELETE</tt>.
2131      Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
2132      encoded requests.
2133      Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
2134      from a model.
2135      All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
2136    </p>
2137
2138    <p>
2139      <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
2140      Instead of requiring server responses to be namespaced under a <tt>model</tt>
2141      key, now you can define your own <a href="#Model-parse">parse</a> method
2142      to convert responses into attributes for Models and Collections.
2143      The old <tt>handleEvents</tt> function is now named
2144      <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
2145      called as part of the View's constructor.
2146      Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
2147      Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
2148    </p>
2149
2150    <p>
2151      <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
2152      Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
2153      attributes of single model from the server.
2154      An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
2155      as an option, which will be invoked if validation fails, overriding the
2156      <tt>"error"</tt> event.
2157      You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
2158      methods by setting <tt>Backbone.emulateHTTP = true</tt>.
2159      Existing Model and Collection data is no longer sent up unnecessarily with
2160      <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
2161      Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
2162    </p>
2163
2164    <p>
2165      <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
2166      Added a convention for <tt>initialize</tt> functions to be called
2167      upon instance construction, if defined. Documentation tweaks.
2168    </p>
2169
2170    <p>
2171      <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
2172      Initial Backbone release.
2173    </p>
2174
2175    <p>
2176      <br />
2177      <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
2178        <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
2179      </a>
2180    </p>
2181
2182  </div>
2183
2184  <script src="test/vendor/underscore-1.1.3.js"></script>
2185  <script src="test/vendor/jquery-1.4.2.js"></script>
2186  <script src="test/vendor/json2.js"></script>
2187  <script src="backbone.js"></script>
2188
2189  <script>
2190    // Set up the "play" buttons for each runnable code example.
2191    $(function() {
2192      $('.runnable').each(function() {
2193        var code = this;
2194        var button = $('<div class="run" title="Run"></div>');
2195        $(button).insertBefore(code).bind('click', function(){
2196          eval($(code).text());
2197        });
2198      });
2199    });
2200  </script>
2201
2202</body>
2203</html>