PageRenderTime 105ms CodeModel.GetById 4ms app.highlight 74ms RepoModel.GetById 2ms app.codeStats 0ms

/node_modules/backbone/index.html

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