PageRenderTime 14ms CodeModel.GetById 5ms app.highlight 55ms RepoModel.GetById 2ms app.codeStats 0ms

/index.html

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