PageRenderTime 9ms CodeModel.GetById 4ms app.highlight 116ms RepoModel.GetById 5ms app.codeStats 1ms

/index.html

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