PageRenderTime 78ms CodeModel.GetById 4ms app.highlight 50ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

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