PageRenderTime 91ms CodeModel.GetById 3ms app.highlight 61ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

https://github.com/StevenBlack/backbone
HTML | 2161 lines | 1854 code | 307 blank | 0 comment | 0 complexity | 7b0456a645b388e3a5841b2a67765515 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
 550    <p id="Model-set">
 551      <b class="header">set</b><code>model.set(attributes, [options])</code>
 552      <br />
 553      Set a hash of attributes (one or many) on the model. If any of the attributes
 554      change the models state, a <tt>"change"</tt> event will be triggered, unless
 555      <tt>{silent: true}</tt> is passed as an option. Change events for specific
 556      attributes are also triggered, and you can bind to those as well, for example:
 557      <tt>change:title</tt>, and <tt>change:content</tt>.
 558    </p>
 559
 560<pre>
 561note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
 562</pre>
 563
 564    <p>
 565      If the model has a <a href="#Model-validate">validate</a> method,
 566      it will be validated before the attributes are set, no changes will
 567      occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
 568      You may also pass an <tt>error</tt>
 569      callback in the options, which will be invoked instead of triggering an
 570      <tt>"error"</tt> event, should validation fail.
 571    </p>
 572
 573    <p id="Model-escape">
 574      <b class="header">escape</b><code>model.escape(attribute)</code>
 575      <br />
 576      Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
 577      of a model's attribute. If you're interpolating data from the model into
 578      HTML, using <b>escape</b> to retrieve attributes will prevent
 579      <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
 580    </p>
 581
 582<pre class="runnable">
 583var hacker = new Backbone.Model({
 584  name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
 585});
 586
 587alert(hacker.escape('name'));
 588</pre>
 589
 590    <p id="Model-has">
 591      <b class="header">has</b><code>model.has(attribute)</code>
 592      <br />
 593      Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
 594      value.
 595    </p>
 596
 597<pre>
 598if (note.has("title")) {
 599  ...
 600}
 601</pre>
 602
 603    <p id="Model-unset">
 604      <b class="header">unset</b><code>model.unset(attribute, [options])</code>
 605      <br />
 606      Remove an attribute by deleting it from the internal attributes hash.
 607      Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
 608    </p>
 609
 610    <p id="Model-clear">
 611      <b class="header">clear</b><code>model.clear([options])</code>
 612      <br />
 613      Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
 614      <tt>silent</tt> is passed as an option.
 615    </p>
 616
 617    <p id="Model-id">
 618      <b class="header">id</b><code>model.id</code>
 619      <br />
 620      A special property of models, the <b>id</b> is an arbitrary string
 621      (integer id or UUID). If you set the <b>id</b> in the
 622      attributes hash, it will be copied onto the model as a direct property.
 623      Models can be retrieved by id from collections, and the id is used to generate
 624      model URLs by default.
 625    </p>
 626
 627    <p id="Model-cid">
 628      <b class="header">cid</b><code>model.cid</code>
 629      <br />
 630      A special property of models, the <b>cid</b> or client id is a unique identifier
 631      automatically assigned to all models when they're first created. Client ids
 632      are handy when the model has not yet been saved to the server, and does not
 633      yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
 634      Client ids take the form: <tt>c1, c2, c3 ...</tt>
 635    </p>
 636
 637    <p id="Model-attributes">
 638      <b class="header">attributes</b><code>model.attributes</code>
 639      <br />
 640      The <b>attributes</b> property is the internal hash containing the model's
 641      state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
 642      them directly. If you'd like to retrieve and munge a copy of the model's
 643      attributes, use <a href="#Model-toJSON">toJSON</a> instead.
 644    </p>
 645
 646    <p id="Model-defaults">
 647      <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
 648      <br />
 649      The <b>defaults</b> hash (or function) can be used to specify the default
 650      attributes for your model. When creating an instance of the model,
 651      any unspecified attributes will be set to their default value.
 652    </p>
 653
 654<pre class="runnable">
 655var Meal = Backbone.Model.extend({
 656  defaults: {
 657    "appetizer":  "caesar salad",
 658    "entree":     "ravioli",
 659    "dessert":    "cheesecake"
 660  }
 661});
 662
 663alert("Dessert will be " + (new Meal).get('dessert'));
 664</pre>
 665
 666    <p id="Model-toJSON">
 667      <b class="header">toJSON</b><code>model.toJSON()</code>
 668      <br />
 669      Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
 670      This can be used for persistence, serialization, or for augmentation before
 671      being handed off to a view. The name of this method is a bit confusing, as
 672      it doesn't actually return a JSON string &mdash; but I'm afraid that it's
 673      the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
 674    </p>
 675
 676<pre class="runnable">
 677var artist = new Backbone.Model({
 678  firstName: "Wassily",
 679  lastName: "Kandinsky"
 680});
 681
 682artist.set({birthday: "December 16, 1866"});
 683
 684alert(JSON.stringify(artist));
 685</pre>
 686
 687    <p id="Model-fetch">
 688      <b class="header">fetch</b><code>model.fetch([options])</code>
 689      <br />
 690      Refreshes the model's state from the server. Useful if the model has never
 691      been populated with data, or if you'd like to ensure that you have the
 692      latest server state. A <tt>"change"</tt> event will be triggered if the
 693      server's state differs from the current attributes. Accepts
 694      <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
 695      are passed <tt>(model, response)</tt> as arguments.
 696    </p>
 697
 698<pre>
 699// Poll every 10 seconds to keep the channel model up-to-date.
 700setInterval(function() {
 701  channel.fetch();
 702}, 10000);
 703</pre>
 704
 705    <p id="Model-save">
 706      <b class="header">save</b><code>model.save([attributes], [options])</code>
 707      <br />
 708      Save a model to your database (or alternative persistence layer),
 709      by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
 710      hash (as in <a href="#Model-set">set</a>) should contain the attributes
 711      you'd like to change -- keys that aren't mentioned won't be altered.
 712      If the model has a <a href="#Model-validate">validate</a>
 713      method, and validation fails, the model will not be saved. If the model
 714      <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
 715      (HTTP <tt>POST</tt>), if the model already
 716      exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
 717    </p>
 718
 719    <p>
 720      In the following example, notice how because the model has never been
 721      saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
 722    </p>
 723
 724<pre class="runnable">
 725Backbone.sync = function(method, model) {
 726  alert(method + ": " + JSON.stringify(model));
 727};
 728
 729var book = new Backbone.Model({
 730  title: "The Rough Riders",
 731  author: "Theodore Roosevelt"
 732});
 733
 734book.save();
 735</pre>
 736
 737    <p>
 738      <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
 739      options hash, which are passed <tt>(model, response)</tt> as arguments.
 740      The <tt>error</tt> callback will also be invoked if the model has a
 741      <tt>validate</tt> method, and validation fails. If a server-side
 742      validation fails, return a non-<tt>200</tt> HTTP response code, along with
 743      an error response in text or JSON.
 744    </p>
 745
 746<pre>
 747book.save({author: "F.D.R."}, {error: function(){ ... }});
 748</pre>
 749
 750    <p id="Model-destroy">
 751      <b class="header">destroy</b><code>model.destroy([options])</code>
 752      <br />
 753      Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
 754      request to <a href="#Sync">Backbone.sync</a>. Accepts
 755      <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
 756    </p>
 757
 758<pre>
 759book.destroy({success: function(model, response) {
 760  ...
 761}});
 762</pre>
 763
 764    <p id="Model-validate">
 765      <b class="header">validate</b><code>model.validate(attributes)</code>
 766      <br />
 767      This method is left undefined, and you're encouraged to override it with
 768      your custom validation logic, if you have any that can be performed
 769      in JavaScript. <b>validate</b> is called before <tt>set</tt> and
 770      <tt>save</tt>, and is passed the attributes that are about to be updated.
 771      If the model and attributes are valid, don't return anything from <b>validate</b>;
 772      if the attributes are invalid, return an error of your choosing. It
 773      can be as simple as a string error message to be displayed, or a complete
 774      error object that describes the error programmatically. <tt>set</tt> and
 775      <tt>save</tt> will not continue if <b>validate</b> returns an error.
 776      Failed validations trigger an <tt>"error"</tt> event.
 777    </p>
 778
 779<pre class="runnable">
 780var Chapter = Backbone.Model.extend({
 781  validate: function(attrs) {
 782    if (attrs.end < attrs.start) {
 783      return "can't end before it starts";
 784    }
 785  }
 786});
 787
 788var one = new Chapter({
 789  title : "Chapter One: The Beginning"
 790});
 791
 792one.bind("error", function(model, error) {
 793  alert(model.get("title") + " " + error);
 794});
 795
 796one.set({
 797  start: 15,
 798  end:   10
 799});
 800</pre>
 801
 802    <p>
 803      <tt>"error"</tt> events are useful for providing coarse-grained error
 804      messages at the model or collection level, but if you have a specific view
 805      that can better handle the error, you may override and suppress the event
 806      by passing an <tt>error</tt> callback directly:
 807    </p>
 808
 809<pre>
 810account.set({access: "unlimited"}, {
 811  error: function(model, error) {
 812    alert(error);
 813  }
 814});
 815</pre>
 816
 817    <p id="Model-url">
 818      <b class="header">url</b><code>model.url()</code>
 819      <br />
 820      Returns the relative URL where the model's resource would be located on
 821      the server. If your models are located somewhere else, override this method
 822      with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
 823      falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
 824    </p>
 825
 826    <p>
 827      Delegates to <a href="#Collection-url">Collection#url</a> to generate the
 828      URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
 829      property, if all models of this class share a common root URL.
 830      A model with an id of <tt>101</tt>, stored in a
 831      <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
 832      would have this URL: <tt>"/documents/7/notes/101"</tt>
 833    </p>
 834
 835    <p id="Model-urlRoot">
 836      <b class="header">urlRoot</b><code>model.urlRoot</code>
 837      <br />
 838      Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
 839      to enable the default <a href="#Model-url">url</a> function to generate
 840      URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
 841    </p>
 842
 843<pre class="runnable">
 844var Book = Backbone.Model.extend({urlRoot : '/books'});
 845
 846var solaris = new Book({id: "1083-lem-solaris"});
 847
 848alert(solaris.url());
 849</pre>
 850
 851    <p id="Model-parse">
 852      <b class="header">parse</b><code>model.parse(response)</code>
 853      <br />
 854      <b>parse</b> is called whenever a model's data is returned by the
 855      server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
 856      The function is passed the raw <tt>response</tt> object, and should return
 857      the attributes hash to be <a href="#Model-set">set</a> on the model. The
 858      default implementation is a no-op, simply passing through the JSON response.
 859      Override this if you need to work with a preexisting API, or better namespace
 860      your responses.
 861    </p>
 862
 863    <p>
 864      If you're working with a Rails backend, you'll notice that Rails' default
 865      <tt>to_json</tt> implementation includes a model's attributes under a
 866      namespace. To disable this behavior for seamless Backbone integration, set:
 867    </p>
 868
 869<pre>
 870ActiveRecord::Base.include_root_in_json = false
 871</pre>
 872
 873    <p id="Model-clone">
 874      <b class="header">clone</b><code>model.clone()</code>
 875      <br />
 876      Returns a new instance of the model with identical attributes.
 877    </p>
 878
 879    <p id="Model-isNew">
 880      <b class="header">isNew</b><code>model.isNew()</code>
 881      <br />
 882      Has this model been saved to the server yet? If the model does not yet have
 883      an <tt>id</tt>, it is considered to be new.
 884    </p>
 885
 886    <p id="Model-change">
 887      <b class="header">change</b><code>model.change()</code>
 888      <br />
 889      Manually trigger the <tt>"change"</tt> event.
 890      If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
 891      aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
 892      when you're all finished.
 893    </p>
 894
 895    <p id="Model-hasChanged">
 896      <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
 897      <br />
 898      Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
 899      is passed, returns <tt>true</tt> if that specific attribute has changed.
 900    </p>
 901
 902<pre>
 903book.bind("change", function() {
 904  if (book.hasChanged("title")) {
 905    ...
 906  }
 907});
 908</pre>
 909
 910    <p id="Model-changedAttributes">
 911      <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
 912      <br />
 913      Retrieve a hash of only the model's attributes that have changed. Optionally,
 914      an external <b>attributes</b> hash can be passed in, returning
 915      the attributes in that hash which differ from the model. This can be used
 916      to figure out which portions of a view should be updated, or what calls
 917      need to be made to sync the changes to the server.
 918    </p>
 919
 920    <p id="Model-previous">
 921      <b class="header">previous</b><code>model.previous(attribute)</code>
 922      <br />
 923      During a <tt>"change"</tt> event, this method can be used to get the
 924      previous value of a changed attribute.
 925    </p>
 926
 927<pre class="runnable">
 928var bill = new Backbone.Model({
 929  name: "Bill Smith"
 930});
 931
 932bill.bind("change:name", function(model, name) {
 933  alert("Changed name from " + bill.previous("name") + " to " + name);
 934});
 935
 936bill.set({name : "Bill Jones"});
 937</pre>
 938
 939    <p id="Model-previousAttributes">
 940      <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
 941      <br />
 942      Return a copy of the model's previous attributes. Useful for getting a
 943      diff between versions of a model, or getting back to a valid state after
 944      an error occurs.
 945    </p>
 946
 947    <h2 id="Collection">Backbone.Collection</h2>
 948
 949    <p>
 950      Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
 951      to be notified when any model in the collection has been modified,
 952      listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
 953      the collection from the server, and use a full suite of
 954      <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
 955    </p>
 956
 957    <p>
 958      Any event that is triggered on a model in a collection will also be
 959      triggered on the collection directly, for convenience.
 960      This allows you to listen for changes to specific attributes in any
 961      model in a collection, for example:
 962      <tt>Documents.bind("change:selected", ...)</tt>
 963    </p>
 964
 965    <p id="Collection-extend">
 966      <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
 967      <br />
 968      To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
 969      providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
 970      directly to the collection's constructor function.
 971    </p>
 972
 973    <p id="Collection-model">
 974      <b class="header">model</b><code>collection.model</code>
 975      <br />
 976      Override this property to specify the model class that the collection
 977      contains. If defined, you can pass raw attributes objects (and arrays) to
 978      <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
 979      and <a href="#Collection-refresh">refresh</a>, and the attributes will be
 980      converted into a model of the proper type.
 981    </p>
 982
 983<pre>
 984var Library = Backbone.Collection.extend({
 985  model: Book
 986});
 987</pre>
 988
 989    <p id="Collection-constructor">
 990      <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
 991      <br />
 992      When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
 993      The collection's <a href="#Collection-comparator">comparator</a> function
 994      may be included as an option. If you define an <b>initialize</b> function, it will be
 995      invoked when the collection is created.
 996    </p>
 997
 998<pre>
 999var tabs = new TabSet([tab1, tab2, tab3]);
1000</pre>
1001
1002    <p id="Collection-models">
1003      <b class="header">models</b><code>collection.models</code>
1004      <br />
1005      Raw access to the JavaScript array of models inside of the collection. Usually you'll
1006      want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
1007      to access model objects, but occasionally a direct reference to the array
1008      is desired.
1009    </p>
1010
1011    <p id="Collection-toJSON">
1012      <b class="header">toJSON</b><code>collection.toJSON()</code>
1013      <br />
1014      Return an array containing the attributes hash of each model in the
1015      collection. This can be used to serialize and persist the
1016      collection as a whole. The name of this method is a bit confusing, because
1017      it conforms to
1018      <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
1019    </p>
1020
1021<pre class="runnable">
1022var collection = new Backbone.Collection([
1023  {name: "Tim", age: 5},
1024  {name: "Ida", age: 26},
1025  {name: "Rob", age: 55}
1026]);
1027
1028alert(JSON.stringify(collection));
1029</pre>
1030
1031    <p id="Collection-Underscore-Methods">
1032      <b class="header">Underscore Methods (25)</b>
1033      <br />
1034      Backbone proxies to <b>Underscore.js</b> to provide 25 iteration functions
1035      on <b>Backbone.Collection</b>. They aren't all documented here, but
1036      you can take a look at the Underscore documentation for the full details&hellip;
1037    </p>
1038
1039    <ul>
1040      <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
1041      <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
1042      <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
1043      <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
1044      <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
1045      <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
1046      <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
1047      <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
1048      <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
1049      <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
1050      <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
1051      <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
1052      <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
1053      <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
1054      <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
1055      <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
1056      <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
1057      <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
1058      <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
1059      <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
1060      <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
1061      <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
1062      <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
1063      <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
1064      <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
1065    </ul>
1066
1067<pre>
1068Books.each(function(book) {
1069  book.publish();
1070});
1071
1072var titles = Books.map(function(book) {
1073  return book.get("title");
1074});
1075
1076var publishedBooks = Books.filter(function(book) {
1077  return book.get("published") === true;
1078});
1079
1080var alphabetical = Books.sortBy(function(book) {
1081  return book.author.get("name").toLowerCase();
1082});
1083</pre>
1084
1085    <p id="Collection-add">
1086      <b class="header">add</b><code>collection.add(models, [options])</code>
1087      <br />
1088      Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
1089      event, which you can pass <tt>{silent: true}</tt> to suppress. If a
1090      <a href="#Collection-model">model</a> property is defined, you may also pass
1091      raw attributes objects.
1092    </p>
1093
1094<pre class="runnable">
1095var ships = new Backbone.Collection;
1096
1097ships.bind("add", function(ship) {
1098  alert("Ahoy " + ship.get("name") + "!");
1099});
1100
1101ships.add([
1102  {name: "Flying Dutchman"},
1103  {name: "Black Pearl"}
1104]);
1105</pre>
1106
1107    <p id="Collection-remove">
1108      <b class="header">remove</b><code>collection.remove(models, [options])</code>
1109      <br />
1110      Remove a model (or an array of models) from the collection. Fires a
1111      <tt>"remove"</tt> event, which you can use <tt>silent</tt>
1112      to suppress.
1113    </p>
1114
1115    <p id="Collection-get">
1116      <b class="header">get</b><code>collection.get(id)</code>
1117      <br />
1118      Get a model from a collection, specified by <b>id</b>.
1119    </p>
1120
1121<pre>
1122var book = Library.get(110);
1123</pre>
1124
1125    <p id="Collection-getByCid">
1126      <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
1127      <br />
1128      Get a model from a collection, specified by client id. The client id
1129      is the <tt>.cid</tt> property of the model, automatically assigned whenever
1130      a model is created. Useful for models which have not yet been saved to
1131      the server, and do not yet have true ids.
1132    </p>
1133
1134    <p id="Collection-at">
1135      <b class="header">at</b><code>collection.at(index)</code>
1136      <br />
1137      Get a model from a collection, specified by index. Useful if your collection
1138      is sorted, and if your collection isn't sorted, <b>at</b> will still
1139      retrieve models in insertion order.
1140    </p>
1141
1142    <p id="Collection-length">
1143      <b class="header">length</b><code>collection.length</code>
1144      <br />
1145      Like an array, a Collection maintains a <tt>length</tt> property, counting
1146      the number of models it contains.
1147    </p>
1148
1149    <p id="Collection-comparator">
1150      <b class="header">comparator</b><code>collection.comparator</code>
1151      <br />
1152      By default there is no <b>comparator</b> function on a collection.
1153      If you define a comparator, it will be used to maintain
1154      the collection in sorted order. This means that as models are added,
1155      they are inserted at the correct index in <tt>collection.models</tt>.
1156      Comparator functions take a model and return a numeric or string value
1157      by which the model should be ordered relative to others.
1158    </p>
1159
1160    <p>
1161      Note how even though all of the chapters in this example are added backwards,
1162      they come out in the proper order:
1163    </p>
1164
1165<pre class="runnable">
1166var Chapter  = Backbone.Model;
1167var chapters = new Backbone.Collection;
1168
1169chapters.comparator = function(chapter) {
1170  return chapter.get("page");
1171};
1172
1173chapters.add(new Chapter({page: 9, title: "The End"}));
1174chapters.add(new Chapter({page: 5, title: "The Middle"}));
1175chapters.add(new Chapter({page: 1, title: "The Beginning"}));
1176
1177alert(chapters.pluck('title'));
1178</pre>
1179
1180    <p class="warning">
1181      Brief aside: This comparator function is different than JavaScript's regular
1182      "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
1183      and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
1184    </p>
1185
1186    <p id="Collection-sort">
1187      <b class="header">sort</b><code>collection.sort([options])</code>
1188      <br />
1189      Force a collection to re-sort itself. You don't need to call this under
1190      normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
1191      will maintain itself in proper sort order at all times. Calling <b>sort</b>
1192      triggers the collection's <tt>"refresh"</tt> event, unless silenced by passing
1193      <tt>{silent: true}</tt>
1194    </p>
1195
1196    <p id="Collection-pluck">
1197      <b class="header">pluck</b><code>collection.pluck(attribute)</code>
1198      <br />
1199      Pluck an attribute from each model in the collection. Equivalent to calling
1200      <tt>map</tt>, and returning a single attribute from the iterator.
1201    </p>
1202
1203<pre class="runnable">
1204var stooges = new Backbone.Collection([
1205  new Backbone.Model({name: "Curly"}),
1206  new Backbone.Model({name: "Larry"}),
1207  new Backbone.Model({name: "Moe"})
1208]);
1209
1210var names = stooges.pluck("name");
1211
1212alert(JSON.stringify(names));
1213</pre>
1214
1215    <p id="Collection-url">
1216      <b class="header">url</b><code>collection.url or collection.url()</code>
1217      <br />
1218      Set the <b>url</b> property (or function) on a collection to reference
1219      its location on the server. Models within the collection will use <b>url</b>
1220      to construct URLs of their own.
1221    </p>
1222
1223<pre>
1224var Notes = Backbone.Collection.extend({
1225  url: '/notes'
1226});
1227
1228// Or, something more sophisticated:
1229
1230var Notes = Backbone.Collection.extend({
1231  url: function() {
1232    return this.document.url() + '/notes';
1233  }
1234});
1235</pre>
1236
1237    <p id="Collection-parse">
1238      <b class="header">parse</b><code>collection.parse(response)</code>
1239      <br />
1240      <b>parse</b> is called by Backbone whenever a collection's models are
1241      returned by the server, in <a href="#Collection-fetch">fetch</a>.
1242      The function is passed the raw <tt>response</tt> object, and should return
1243      the array of model attributes to be <a href="#Collection-add">added</a>
1244      to the collection. The default implementation is a no-op, simply passing
1245      through the JSON response. Override this if you need to work with a
1246      preexisting API, or better namespace your responses.
1247    </p>
1248
1249<pre>
1250var Tweets = Backbone.Collection.extend({
1251  // The Twitter Search API returns tweets under "results".
1252  parse: function(response) {
1253    return response.results;
1254  }
1255});
1256</pre>
1257
1258    <p id="Collection-fetch">
1259      <b class="header">fetch</b><code>collection.fetch([options])</code>
1260      <br />
1261      Fetch the default set of models for this collection from the server,
1262      refreshing the collection when they arrive. The <b>options</b> hash takes
1263      <tt>success</tt> and <tt>error</tt>
1264      callbacks which will be passed <tt>(collection, response)</tt> as arguments.
1265      When the model data returns from the server, the collection will
1266      <a href="#Collection-refresh">refresh</a>.
1267      Delegates to <a href="#Sync">Backbone.sync</a>
1268      under the covers, for custom persistence strategies.
1269      The server handler for <b>fetch</b> requests should return a JSON array of
1270      models.
1271    </p>
1272
1273<pre class="runnable">
1274Backbone.sync = function(method, model) {
1275  alert(method + ": " + model.url);
1276};
1277
1278var Accounts = new Backbone.Collection;
1279Accounts.url = '/accounts';
1280
1281Accounts.fetch();
1282</pre>
1283
1284    <p>
1285      If you'd like to add the incoming models to the current collection, instead
1286      of replacing the collection's contents, pass <tt>{add: true}</tt> as an
1287      option to <b>fetch</b>.
1288    </p>
1289
1290    <p>
1291      Note that <b>fetch</b> should not be used to populate collections on
1292      page load &mdash; all models needed at load time should already be
1293      <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
1294      intended for lazily-loading models for interfaces that are not needed
1295      immediately: for example, documents with collections of notes that may be
1296      toggled open and closed.
1297    </p>
1298
1299    <p id="Collection-refresh">
1300      <b class="header">refresh</b><code>collection.refresh(models, [options])</code>
1301      <br />
1302      Adding and removing models one at a time is all well and good, but sometimes
1303      you have so many models to change that you'd rather just update the collection
1304      in bulk. Use <b>refresh</b> to replace a collection with a new list
1305      of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
1306      at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
1307    </p>
1308
1309    <p>
1310      Here's an example using <b>refresh</b> to bootstrap a collection during initial page load,
1311      in a Rails application.
1312    </p>
1313
1314<pre>
1315&lt;script&gt;
1316  Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
1317&lt;/script&gt;
1318</pre>
1319
1320    <p id="Collection-create">
1321      <b class="header">create</b><code>collection.create(attributes, [options])</code>
1322      <br />
1323      Convenience to create a new instance of a model within a collection.
1324      Equivalent to instantiating a model with a hash of attributes,
1325      saving the model to the server, and adding the model to the set after being
1326      successfully created. Returns
1327      the model, or <tt>false</tt> if a validation error prevented the
1328      model from being created. In order for this to work, your should set the
1329      <a href="#Collection-model">model</a> property of the collection.
1330    </p>
1331
1332<pre>
1333var Library = Backbone.Collection.extend({
1334  model: Book
1335});
1336
1337var NYPL = new Library;
1338
1339var othello = NYPL.create({
1340  title: "Othello",
1341  author: "William Shakespeare"
1342});
1343</pre>
1344
1345    <h2 id="Controller">Backbone.Controller</h2>
1346
1347    <p>
1348      Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
1349      in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
1350      <b>Backbone.Controller</b> provides methods for routing client-side URL
1351      fragments, and connecting them to actions and events.
1352    </p>
1353
1354    <p class="warning">
1355      Backbone controllers do not yet make use of HTML5 <b>pushState</b> and
1356      <b>replaceState</b>. Currently, <b>pushState</b> and <b>replaceState</b>
1357      need special handling on the server-side, cause you to mint duplicate URLs,
1358      and have an incomplete API. We may start supporting them in the future
1359      when these issues have been resolved.
1360    </p>
1361
1362    <p>
1363      During page load, after your application has finished creating all of its controllers,
1364      be sure to call <tt>Backbone.history.start()</tt> to route the initial URL.
1365    </p>
1366
1367    <p id="Controller-extend">
1368      <b class="header">extend</b><code>Backbone.Controller.extend(properties, [classProperties])</code>
1369      <br />
1370      Get started by creating a custom controller class. You'll
1371      want to define actions that are triggered when certain URL fragments are
1372      matched, and provide a <a href="#Controller-routes">routes</a> hash
1373      that pairs routes to actions.
1374    </p>
1375
1376<pre>
1377var Workspace = Backbone.Controller.extend({
1378
1379  routes: {
1380    "help":                 "help",    // #help
1381    "search/:query":        "search",  // #search/kiwis
1382    "search/:query/p:page": "search"   // #search/kiwis/p7
1383  },
1384
1385  help: function() {
1386    ...
1387  },
1388
1389  search: function(query, page) {
1390    ...
1391  }
1392
1393});
1394</pre>
1395
1396    <p id="Controller-routes">
1397      <b class="header">routes</b><code>controller.routes</code>
1398      <br />
1399      The routes hash maps URLs with parameters to functions on your controller,
1400      similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
1401      Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
1402      component between slashes; and splat parts <tt>*splat</tt>, which can match
1403      any number of URL components.
1404    </p>
1405
1406    <p>
1407      For example, a route of <tt>"search/:query/p:page"</tt> will match
1408      a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
1409      and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
1410      match <tt>#file/nested/folder/file.txt</tt>,
1411      passing <tt>"nested/folder/file.txt"</tt> to the action.
1412    </p>
1413
1414    <p>
1415      When the visitor presses the back button, or enters a URL, and a particular
1416      route is matched, the name of the action will be fired as an
1417      <a href="#Events">event</a>, so that other objects can listen to the controller,
1418      and be notified. In the following example, visiting <tt>#help/uploading</tt>
1419      will fire a <tt>route:help</tt> event from the controller.
1420    </p>
1421
1422<pre>
1423routes: {
1424  "help/:page":         "help",
1425  "download/*path":     "download",
1426  "folder/:name":       "openFolder",
1427  "folder/:name-:mode": "openFolder"
1428}
1429</pre>
1430
1431<pre>
1432controller.bind("route:help", function(page) {
1433  ...
1434});
1435</pre>
1436
1437    <p id="Controller-constructor">
1438      <b class="header">constructor / initialize</b><code>new Controller([options])</code>
1439      <br />
1440      When creating a new controller, you may pass its
1441      <a href="#Controller-routes">routes</a> hash directly as an option, if you
1442      choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
1443      function, if defined.
1444    </p>
1445
1446    <p id="Controller-route">
1447      <b class="header">route</b><code>controller.route(route, name, callback)</code>
1448      <br />
1449      Manually create a route for the controller, The <tt>route</tt> argument may
1450      be a <a href="#Controller-routes">routing string</a> or regular expression.
1451      Each matching capture from the route or regular expression will be passed as
1452      an argument to the callback. The <tt>name</tt> argument will be triggered as
1453      a <tt>"route:name"</tt> event whenever the route is matched.
1454    </p>
1455
1456<pre>
1457initialize: function(options) {
1458
1459  // Matches #page/10, passing "10"
1460  this.route("page/:number", "page", function(number){ ... });
1461
1462  // Matches /117-a/b/c/open, passing "117-a/b/c"
1463  this.route(/^(.*?)\/open$/, "open", function(id){ ... });
1464
1465}
1466</pre>
1467
1468    <p id="Controller-saveLocation">
1469      <b class="header">saveLocation</b><code>controller.saveLocation(fragment)</code>
1470      <br />
1471      Whenever you reach a point in your application that you'd like to save
1472      as a URL, call <b>saveLocation</b> in order to update the URL fragment
1473      without triggering a <tt>hashchange</tt> event. (If you would prefer to
1474      trigger the event and routing, you can just set the hash directly.)
1475    </p>
1476
1477<pre>
1478openPage: function(pageNumber) {
1479  this.document.pages.at(pageNumber).open();
1480  this.saveLocation("page/" + pageNumber);
1481}
1482</pre>
1483
1484    <h2 id="History">Backbone.history</h2>
1485
1486    <p>
1487      <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
1488      events, match the appropriate route, and trigger callbacks. You shouldn't
1489      ever have to create one of these yourself &mdash; you should use the reference
1490      to <tt>Backbone.history</tt> that will be created for you automatically if you make use
1491      of <a href="#Controller">Controllers</a> with <a href="#Controller-routes">routes</a>.
1492    </p>
1493
1494    <p id="History-start">
1495      <b class="header">start</b><code>Backbone.history.start()</code>
1496      <br />
1497      When all of your <a href="#Controller">Controllers</a> have been created,
1498      and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
1499      to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
1500    </p>
1501
1502<pre>
1503$(function(){
1504  new WorkspaceController();
1505  new HelpPaneController();
1506  Backbone.history.start();
1507});
1508</pre>
1509
1510    <h2 id="Sync">Backbone.sync</h2>
1511
1512    <p>
1513      <b>Backbone.sync</b> is the function the Backbone calls every time it
1514      attempts to read or save a model to the server. By default, it uses
1515      <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request. You can override
1516      it in order to use a different persistence strategy, such as WebSockets,
1517      XML transport, or Local Storage.
1518    </p>
1519
1520    <p>
1521      The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, success, error)</tt>
1522    </p>
1523
1524    <ul>
1525      <li><b>method</b> – the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
1526      <li><b>model</b> – the model to be saved (or collection to be read)</li>
1527      <li><b>success({model: ...})</b> – a callback that should be fired if the request works</li>
1528      <li><b>error({model: ...})</b> – a callback that should be fired if the request fails</li>
1529    </ul>
1530
1531    <p>
1532      With the default implementation, when <b>Backbone.sync</b> sends up a request to save
1533      a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
1534      with content-type <tt>application/json</tt>. When returning a JSON response,
1535      send down the attributes of the  model that have been changed by the server, and need
1536      to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
1537      (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
1538      of model attribute objects.
1539    </p>
1540
1541    <p>
1542      The default <b>sync</b> handler maps CRUD to REST like so:
1543    </p>
1544
1545    <ul>
1546      <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
1547      <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
1548      <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
1549      <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
1550    </ul>
1551
1552    <p>
1553      As an example, a Rails handler responding to an <tt>"update"</tt> call from
1554      <tt>Backbone</tt> might look like this: <i>(In real code, never use
1555      </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
1556      you allow to be changed.)</i>
1557    </p>
1558
1559<pre>
1560def update
1561  account = Account.find params[:id]
1562  account.update_attributes params
1563  render :json => account
1564end
1565</pre>
1566
1567    <p>
1568      One more tip for Rails integration is to disable the default namespacing for
1569      <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
1570    </p>
1571
1572    <p id="Sync-emulateHTTP">
1573      <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
1574      <br />
1575      If you want to work with a legacy web server that doesn't support Backbones's
1576      default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
1577      Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
1578      a HTTP <tt>POST</tt>, and pass them under the <tt>_method</tt> parameter. Setting this option
1579      will also set an <tt>X-HTTP-Method-Override</tt> header with the true method.
1580    </p>
1581
1582<pre>
1583Backbone.emulateHTTP = true;
1584
1585model.save();  // POST to "/collection/id", with "_method=PUT" + header.
1586</pre>
1587
1588    <p id="Sync-emulateJSON">
1589      <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
1590      <br />
1591      If you're working with a legacy web server that can't handle requests
1592      encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
1593      will cause the JSON to be serialized under a <tt>model</tt> parameter, and
1594      the request to be made with a <tt>application/x-www-form-urlencoded</tt>
1595      mime type, as if from an HTML form.
1596    </p>
1597
1598    <h2 id="View">Backbone.View</h2>
1599
1600    <p>
1601      Backbone views are almost more convention than they are code &mdash; they
1602      don't determine anything about your HTML or CSS for you, and can be used
1603      with any JavaScript templating library.
1604      The general idea is to organize your interface into logical views,
1605      backed by models, each of which can be updated independently when the
1606      model changes, without having to redraw the page. Instead of digging into
1607      a JSON object, looking up an element in the DOM, and updating the HTML by hand,
1608      you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
1609      event &mdash; and now everywhere that
1610      model data is displayed in the UI, it is always immediately up to date.
1611    </p>
1612
1613    <p id="View-extend">
1614      <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
1615      <br />
1616      Get started with views by creating a custom view class. You'll want to
1617      override the <a href="#View-render">render</a> function, specify your
1618      declarative <a href="#View-delegateEvents">events</a>, and perhaps the
1619      <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
1620      element.
1621    </p>
1622
1623<pre>
1624var DocumentRow = Backbone.View.extend({
1625
1626  tagName: "li",
1627
1628  className: "document-row",
1629
1630  events: {
1631    "click .icon":          "open",
1632    "click .button.edit":   "openEditDialog",
1633    "click .button.delete": "destroy"
1634  },
1635
1636  initialize: function() {
1637    _.bindAll(this, "render");
1638  },
1639
1640  render: function() {
1641    ...
1642  }
1643
1644});
1645</pre>
1646
1647    <p id="View-constructor">
1648      <b class="header">constructor / initialize</b><code>new View([options])</code>
1649      <br />
1650      When creating a new View, the options you pass are attached to the view
1651      as <tt>this.options</tt>, for future reference. There are several special
1652      options that, if passed, will be attached directly to the view:
1653      <tt>model</tt>, <tt>collection</tt>,
1654      <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, and <tt>tagName</tt>.
1655      If the view defines an <b>initialize</b> function, it will be called when
1656      the view is first created. If you'd like to create a view that references
1657      an element <i>already</i> in the DOM, pass in the element as an option:
1658      <tt>new View({el: existingElement})</tt>
1659    </p>
1660
1661<pre>
1662var doc = Documents.first();
1663
1664new DocumentRow({
1665  model: doc,
1666  id: "document-row-" + doc.id
1667});
1668</pre>
1669
1670    <p id="View-el">
1671      <b class="header">el</b><code>view.el</code>
1672      <br />
1673      All views have a DOM element at all times (the <b>el</b> property),
1674      whether they've already been inserted into the page or not. In this
1675      fashion, views can be rendered at any time, and inserted into the DOM all
1676      at once, in order to get high-performance UI rendering with as few
1677      reflows and repaints as possible. <tt>this.el</tt> is created from the
1678      view's <tt>tagName</tt>, <tt>className</tt>, and <tt>id</tt> properties,
1679      if specified. If not, <b>el</b> is an empty <tt>div</tt>.
1680    </p>
1681
1682    <p>
1683      You may assign <b>el</b> directly if the view is being
1684      created for an element that already exists in the DOM. Use either a
1685      reference to a real DOM element, or a css selector string.
1686    </p>
1687
1688<pre class="runnable">
1689var ItemView = Backbone.View.extend({
1690  tagName: 'li'
1691});
1692
1693var BodyView = Backbone.View.extend({
1694  el: 'body'
1695});
1696
1697var item = new ItemView();
1698var body = new BodyView();
1699
1700alert(item.el + ' ' + body.el);
1701</pre>
1702
1703    <p id="View-dollar">
1704      <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
1705      <br />
1706      If jQuery or Zepto is included on the page, each view has a
1707      <b>$</b> function that runs queries scoped within the view's element. If you use this
1708      scoped jQuery function, you don't have to use model ids as part of your query
1709      to pull out specific elements in a list, and can rely much more on HTML class
1710      attributes. It's equivalent to running: <tt>$(selector, this.el)</tt>
1711    </p>
1712
1713<pre>
1714ui.Chapter = Backbone.View.extend({
1715  serialize : function() {
1716    return {
1717      title: this.$(".title").text(),
1718      start: this.$(".start-page").text(),
1719      end:   this.$(".end-page").text()
1720    };
1721  }
1722});
1723</pre>
1724
1725    <p id="View-render">
1726      <b class="header">render</b><code>view.render()</code>
1727      <br />
1728      The default implementation of <b>render</b> is a no-op. Override this
1729      function with your code that renders the view template from model data,
1730      and updates <tt>this.el</tt> with the new HTML. A good
1731      convention is to <tt>return this</tt> at the end of <b>render</b> to
1732      enable chained calls.
1733    </p>
1734
1735<pre>
1736var Bookmark = Backbone.View.extend({
1737  render: function() {
1738    $(this.el).html(this.template(this.model.toJSON()));
1739    return this;
1740  }
1741});
1742</pre>
1743
1744    <p>
1745      Backbone is agnostic with respect to your preferred method of HTML templating.
1746      Your <b>render</b> function could even munge together an HTML string, or use
1747      <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
1748      choosing a nice JavaScript templating library.
1749      <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
1750      <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
1751      <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
1752      Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
1753      <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
1754      is available, and is an excellent choice if you've already XSS-sanitized
1755      your interpolated data.
1756    </p>
1757
1758    <p>
1759      Whatever templating strategy you end up with, it's nice if you <i>never</i>
1760      have to put strings of HTML in your JavaScript. At DocumentCloud, we
1761      use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
1762      to package up JavaScript templates stored in <tt>/app/views</tt> as part
1763      of our main <tt>core.js</tt> asset package.
1764    </p>
1765
1766    <p id="View-remove">
1767      <b class="header">remove</b><code>view.remove()</code>
1768      <br />
1769      Convenience function for removing the view from the DOM. Equivalent to calling
1770      <tt>$(view.el).remove();</tt>
1771    </p>
1772
1773    <p id="View-make">
1774      <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
1775      <br />
1776      Convenience function for creating a DOM element of the given type (<b>tagName</b>),
1777      with optional attributes and HTML content. Used internally to create the
1778      initial <tt>view.el</tt>.
1779    </p>
1780
1781<pre class="runnable">
1782var view = new Backbone.View;
1783
1784var el = view.make("b", {className: "bold"}, "Bold! ");
1785
1786$("#make-demo").append(el);
1787</pre>
1788
1789<div id="make-demo"></div>
1790
1791    <p id="View-delegateEvents">
1792      <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
1793      <br />
1794      Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
1795      for DOM events within a view.
1796      If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
1797      as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
1798      Omitting the <tt>selector</tt> causes the event to be bound to the view's
1799      root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
1800      within the View's constructor for you, so if you have a simple <tt>events</tt>
1801      hash, all of your DOM events will always already be connected, and you will
1802      never have to call this function yourself.
1803    </p>
1804
1805    <p>
1806      Using <b>delegateEvents</b> provides a number of advantages over manually
1807      using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
1808      callbacks are bound to the view before being handed off to jQuery, so when
1809      the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
1810      <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
1811      hash, all callbacks are removed and delegated afresh &mdash; useful for
1812      views which need to behave differently when in different modes.
1813    </p>
1814
1815    <p>
1816      A view that displays a document in a search result might look
1817      something like this:
1818    </p>
1819
1820<pre>
1821var DocumentView = Backbone.View.extend({
1822
1823  events: {
1824    "dblclick"                : "open",
1825    "click .icon.doc"         : "select",
1826    "contextmenu .icon.doc"   : "showMenu",
1827    "click .show_notes"       : "toggleNotes",
1828    "click .title .lock"      : "editAccessLevel",
1829    "mouseover .title .date"  : "showTooltip"
1830  },
1831
1832  render: function() {
1833    $(this.el).html(this.template(this.model.toJSON()));
1834    return this;
1835  },
1836
1837  open: function() {
1838    window.open(this.model.get("viewer_url"));
1839  },
1840
1841  select: function() {
1842    this.model.set({selected: true});
1843  },
1844
1845  ...
1846
1847});
1848</pre>
1849
1850    <h2 id="examples">Examples</h2>
1851
1852    <p>
1853      <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
1854      <a href="examples/todos/index.html">Todo List application</a>
1855      that is bundled in the repository as Backbone example. If you're wondering
1856      where to get started with Backbone in general, take a moment to
1857      <a href="docs/todos.html">read through the annotated source</a>. The app uses a
1858      <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
1859      to transparently save all of your todos within your browser, instead of
1860      sending them to a server. Jérôme also has a version hosted at
1861      <a href="http://localtodos.com/">localtodos.com</a> that uses a
1862      <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
1863      instead of jQuery.
1864    </p>
1865
1866    <div style="text-align: center;">
1867      <a href="examples/todos/index.html">
1868        <img src="docs/images/todos.png" alt="Todos" class="example_image" />
1869      </a>
1870    </div>
1871
1872    <p>
1873      The <a href="http://www.documentcloud.org/">DocumentCloud</a> workspace
1874      is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
1875      <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
1876    </p>
1877
1878    <div style="text-align: center;">
1879      <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" class="example_image" />
1880    </div>
1881
1882    <p>
1883      <a href="http://bennolan.com/">Ben Nolan</a> created
1884      <a href="http://bennolan.com/2010/11/24/backbone-jquery-demo.html">an example "Backbone Mobile" application</a>, combining Backbone.js
1885      with <a href="http://jquerymobile.com/">jQuery Mobile</a>. You can
1886      <a href="http://bennolan.com/science/backbone-mobile/">try the app</a>
1887      in your browser, or view the
1888      <a href="https://github.com/bnolan/backbone-mobile">source code</a> on Github.
1889    </p>
1890
1891    <div style="text-align: center;">
1892      <a href="http://bennolan.com/science/backbone-mobile/">
1893        <img src="docs/images/backbone-mobile.png" alt="Backbone Mobile" class="example_image" />
1894      </a>
1895    </div>
1896
1897    <p>
1898      <a href="http://www.twitter.com/jamesjyu">James Yu</a> used Backbone.js to
1899      create <a href="http://www.quietwrite.com/">QuietWrite</a>, an app
1900      that gives writers a clean and quiet interface to concentrate on the text itself.
1901      It also works great on the iPad. The editor relies on
1902      Backbone to persist document data to the server.
1903    </p>
1904
1905    <div style="text-align: center;">
1906      <a href="http://www.quietwrite.com/">
1907        <img src="docs/images/quietwrite.png" alt="QuietWrite" class="example_image" />
1908      </a>
1909    </div>
1910
1911    <h2 id="faq">F.A.Q.</h2>
1912
1913    <p id="FAQ-events">
1914      <b class="header">Catalog of Events</b>
1915      <br />
1916      Here's a list of all of the built-in events that Backbone.js can fire.
1917      You're also free to trigger your own events on Models and Views as you
1918      see fit.
1919    </p>
1920
1921    <ul>
1922      <li><b>"add"</b> (model, collection) &mdash; when a model is added to a collection. </li>
1923      <li><b>"remove"</b> (model, collection) &mdash; when a model is removed from a collection. </li>
1924      <li><b>"refresh"</b> (collection) &mdash; when the collection's entire contents have been replaced. </li>
1925      <li><b>"change"</b> (model, collection) &mdash; when a model's attributes have changed. </li>
1926      <li><b>"change:[attribute]"</b> (model, collection) &mdash; when a specific attribute has been updated. </li>
1927      <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>
1928      <li><b>"route:[name]"</b> (controller) &mdash; when one of a controller's routes has matched. </li>
1929      <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
1930    </ul>
1931
1932    <p id="FAQ-nested">
1933      <b class="header">Nested Models &amp; Collections</b>
1934      <br />
1935      It's common to nest collections inside of models with Backbone. For example,
1936      consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
1937      One nice pattern for handling this is have a <tt>this.messages</tt> collection
1938      for each mailbox, enabling the lazy-loading of messages, when the mailbox
1939      is first opened ... perhaps with <tt>MessageList</tt> views listening for
1940      <tt>"add"</tt> and <tt>"remove"</tt> events.
1941    </p>
1942
1943<pre>
1944var Mailbox = Backbone.Model.extend({
1945
1946  initialize: function() {
1947    this.messages = new Messages;
1948    this.messages.url = '/mailbox/' + this.id + '/messages';
1949    this.messages.bind("refresh", this.updateCounts);
1950  },
1951
1952  ...
1953
1954});
1955
1956var Inbox = new Mailbox;
1957
1958// And then, when the Inbox is opened:
1959
1960Inbox.messages.fetch();
1961</pre>
1962
1963    <p id="FAQ-bootstrap">
1964      <b class="header">Loading Bootstrapped Models</b>
1965      <br />
1966      When your app first loads, it's common to have a set of initial models that
1967      you know you're going to need, in order to render the page. Instead of
1968      firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
1969      a nicer pattern is to have their data already bootstrapped into the page.
1970      You can then use <a href="#Collection-refresh">refresh</a> to populate your
1971      collections with the initial data. At DocumentCloud, in the
1972      <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
1973      workspace, we do something along these lines:
1974    </p>
1975
1976<pre>
1977&lt;script&gt;
1978  Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
1979  Projects.refresh(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
1980&lt;/script&gt;
1981</pre>
1982
1983    <p id="FAQ-mvc">
1984      <b class="header">How does Backbone relate to "traditional" MVC?</b>
1985      <br />
1986      Different implementations of the
1987      <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
1988      pattern tend to disagree about the definition of a controller. If it helps any, in
1989      Backbone, the <a href="#View">View</a> class can also be thought of as a
1990      kind of controller, dispatching events that originate from the UI, with
1991      the HTML template serving as the true view. We call it a View because it
1992      represents a logical chunk of UI, responsible for the contents of a single
1993      DOM element.
1994    </p>
1995
1996    <p id="FAQ-this">
1997      <b class="header">Binding "this"</b>
1998      <br />
1999      Perhaps the single most common JavaScript "gotcha" is the fact that when
2000      you pass a function as a callback, it's value for <tt>this</tt> is lost. With
2001      Backbone, when dealing with <a href="#Events">events</a> and callbacks,
2002      you'll often find it useful to rely on
2003      <a href="http://documentcloud.github.com/underscore/#bind">_.bind</a> and
2004      <a href="http://documentcloud.github.com/underscore/#bindAll">_.bindAll</a>
2005      from Underscore.js. <tt>_.bind</tt> takes a function and an object to be
2006      used as <tt>this</tt>, any time the function is called in the future.
2007      <tt>_.bindAll</tt> takes an object and a list of method names: each method
2008      in the list will be bound to the object, so that it's <tt>this</tt> may
2009      not change. For example, in a <a href="#View">View</a> that listens for
2010      changes to a collection...
2011    </p>
2012
2013<pre>
2014var MessageList = Backbone.View.extend({
2015
2016  initialize: function() {
2017    _.bindAll(this, "addMessage", "removeMessage", "render");
2018
2019    var messages = this.collection;
2020    messages.bind("refresh", this.render);
2021    messages.bind("add", this.addMessage);
2022    messages.bind("remove", this.removeMessage);
2023  }
2024
2025});
2026
2027// Later, in the app...
2028
2029Inbox.messages.add(newMessage);
2030</pre>
2031
2032    <p id="FAQ-rias">
2033      <b class="header">
2034        How is Backbone different than
2035        <a href="http://www.sproutcore.com/">SproutCore</a> or
2036        <a href="http://cappuccino.org/">Cappuccino</a>?
2037      </b>
2038      <br />
2039      This question is frequently asked, and all three projects apply general
2040      <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
2041      principles to JavaScript applications. However, there isn't much basis
2042      for comparison. SproutCore and Cappuccino provide rich UI widgets, vast
2043      core libraries, and determine the structure of your HTML for you.
2044      Both frameworks measure in the hundreds of kilobytes when packed and
2045      gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser
2046      &mdash; there's a lot of room underneath for libraries of a more moderate scope.
2047      Backbone is a <i>4 kilobyte</i> include that provides
2048      just the core concepts of models, events, collections, views, controllers,
2049      and persistence.
2050    </p>
2051
2052    <h2 id="changelog">Change Log</h2>
2053
2054    <p>
2055      <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
2056      Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
2057      jQuery, as a framework for DOM manipulation and Ajax support.
2058      Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
2059      attributes intended for HTML interpolation. When trying to persist a model,
2060      failed requests will now trigger an <tt>"error"</tt> event. The
2061      ubiquitous <tt>options</tt> argument is now passed as the final argument
2062      to all <tt>"change"</tt> events.
2063    </p>
2064
2065    <p>
2066      <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
2067      Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
2068      overridden on a per-model, or per-collection basis. Fixed recursion error
2069      when calling <tt>save</tt> with no changed attributes, within a
2070      <tt>"change"</tt> event.
2071    </p>
2072
2073    <p>
2074      <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
2075      All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
2076      model, so that views can listen for them without having to know about the
2077      collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
2078      <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
2079      Backbone routes are now able to load empty URL fragments.
2080    </p>
2081
2082    <p>
2083      <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
2084      Backbone now has <a href="#Controller">Controllers</a> and
2085      <a href="#History">History</a>, for doing client-side routing based on
2086      URL fragments.
2087      Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
2088      do <tt>PUT</tt> and <tt>DELETE</tt>.
2089      Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
2090      encoded requests.
2091      Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
2092      from a model.
2093      All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
2094    </p>
2095
2096    <p>
2097      <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
2098      Instead of requiring server responses to be namespaced under a <tt>model</tt>
2099      key, now you can define your own <a href="#Model-parse">parse</a> method
2100      to convert responses into attributes for Models and Collections.
2101      The old <tt>handleEvents</tt> function is now named
2102      <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
2103      called as part of the View's constructor.
2104      Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
2105      Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
2106    </p>
2107
2108    <p>
2109      <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
2110      Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
2111      attributes of single model from the server.
2112      An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
2113      as an option, which will be invoked if validation fails, overriding the
2114      <tt>"error"</tt> event.
2115      You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
2116      methods by setting <tt>Backbone.emulateHTTP = true</tt>.
2117      Existing Model and Collection data is no longer sent up unnecessarily with
2118      <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
2119      Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
2120    </p>
2121
2122    <p>
2123      <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
2124      Added a convention for <tt>initialize</tt> functions to be called
2125      upon instance construction, if defined. Documentation tweaks.
2126    </p>
2127
2128    <p>
2129      <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
2130      Initial Backbone release.
2131    </p>
2132
2133    <p>
2134      <br />
2135      <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
2136        <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
2137      </a>
2138    </p>
2139
2140  </div>
2141
2142  <script src="test/vendor/underscore-1.1.3.js"></script>
2143  <script src="test/vendor/jquery-1.4.2.js"></script>
2144  <script src="test/vendor/json2.js"></script>
2145  <script src="backbone.js"></script>
2146
2147  <script>
2148    // Set up the "play" buttons for each runnable code example.
2149    $(function() {
2150      $('.runnable').each(function() {
2151        var code = this;
2152        var button = $('<div class="run" title="Run"></div>');
2153        $(button).insertBefore(code).bind('click', function(){
2154          eval($(code).text());
2155        });
2156      });
2157    });
2158  </script>
2159
2160</body>
2161</html>