PageRenderTime 51ms CodeModel.GetById 4ms app.highlight 30ms RepoModel.GetById 2ms app.codeStats 0ms

/index.html

https://github.com/jetleigh/backbone
HTML | 3036 lines | 2597 code | 439 blank | 0 comment | 0 complexity | c41c0c28aa6506b7e5577a2ac199b36a MD5 | raw file

Large files files are truncated, but you can click here to view the full 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 #bbb;
  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-idAttribute">idAttribute</a></li>
 182      <li><a href="#Model-cid">cid</a></li>
 183      <li><a href="#Model-attributes">attributes</a></li>
 184      <li><a href="#Model-defaults">defaults</a></li>
 185      <li>- <a href="#Model-toJSON">toJSON</a></li>
 186      <li><a href="#Model-fetch">fetch</a></li>
 187      <li><a href="#Model-save">save</a></li>
 188      <li><a href="#Model-destroy">destroy</a></li>
 189      <li><a href="#Model-validate">validate</a></li>
 190      <li><a href="#Model-url">url</a></li>
 191      <li><a href="#Model-urlRoot">urlRoot</a></li>
 192      <li><a href="#Model-parse">parse</a></li>
 193      <li><a href="#Model-clone">clone</a></li>
 194      <li><a href="#Model-isNew">isNew</a></li>
 195      <li><a href="#Model-change">change</a></li>
 196      <li><a href="#Model-hasChanged">hasChanged</a></li>
 197      <li><a href="#Model-changedAttributes">changedAttributes</a></li>
 198      <li><a href="#Model-previous">previous</a></li>
 199      <li><a href="#Model-previousAttributes">previousAttributes</a></li>
 200    </ul>
 201
 202    <a class="toc_title" href="#Collection">
 203      Collection
 204    </a>
 205    <ul class="toc_section">
 206      <li><a href="#Collection-extend">extend</a></li>
 207      <li><a href="#Collection-model">model</a></li>
 208      <li><a href="#Collection-constructor">constructor / initialize</a></li>
 209      <li><a href="#Collection-models">models</a></li>
 210      <li><a href="#Collection-toJSON">toJSON</a></li>
 211      <li><a href="#Collection-Underscore-Methods"><b>Underscore Methods (26)</b></a></li>
 212      <li><a href="#Collection-add">add</a></li>
 213      <li><a href="#Collection-remove">remove</a></li>
 214      <li><a href="#Collection-get">get</a></li>
 215      <li><a href="#Collection-getByCid">getByCid</a></li>
 216      <li><a href="#Collection-at">at</a></li>
 217      <li><a href="#Collection-length">length</a></li>
 218      <li><a href="#Collection-comparator">comparator</a></li>
 219      <li><a href="#Collection-sort">sort</a></li>
 220      <li><a href="#Collection-pluck">pluck</a></li>
 221      <li><a href="#Collection-url">url</a></li>
 222      <li><a href="#Collection-parse">parse</a></li>
 223      <li><a href="#Collection-fetch">fetch</a></li>
 224      <li><a href="#Collection-reset">reset</a></li>
 225      <li><a href="#Collection-create">create</a></li>
 226    </ul>
 227
 228    <a class="toc_title" href="#Router">
 229      Router
 230    </a>
 231    <ul class="toc_section">
 232      <li><a href="#Router-extend">extend</a></li>
 233      <li><a href="#Router-routes">routes</a></li>
 234      <li><a href="#Router-constructor">constructor / initialize</a></li>
 235      <li><a href="#Router-route">route</a></li>
 236      <li><a href="#Router-navigate">navigate</a></li>
 237    </ul>
 238
 239    <a class="toc_title" href="#History">
 240      History
 241    </a>
 242    <ul class="toc_section">
 243      <li><a href="#History-start">start</a></li>
 244    </ul>
 245
 246    <a class="toc_title" href="#Sync">
 247      Sync
 248    </a>
 249    <ul class="toc_section">
 250      <li><a href="#Sync">Backbone.sync</a></li>
 251      <li><a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
 252      <li><a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
 253    </ul>
 254
 255    <a class="toc_title" href="#View">
 256      View
 257    </a>
 258    <ul class="toc_section">
 259      <li><a href="#View-extend">extend</a></li>
 260      <li><a href="#View-constructor">constructor / initialize</a></li>
 261      <li><a href="#View-el">el</a></li>
 262      <li><a href="#View-dollar">$ (jQuery or Zepto)</a></li>
 263      <li><a href="#View-render">render</a></li>
 264      <li><a href="#View-remove">remove</a></li>
 265      <li><a href="#View-make">make</a></li>
 266      <li><a href="#View-delegateEvents">delegateEvents</a></li>
 267    </ul>
 268
 269    <a class="toc_title" href="#Utility">
 270      Utility
 271    </a>
 272    <ul class="toc_section">
 273      <li><a href="#Utility-noConflict">noConflict</a></li>
 274    </ul>
 275
 276    <a class="toc_title" href="#examples">
 277      Examples
 278    </a>
 279    <ul class="toc_section">
 280      <li><a href="#examples-todos">Todos</a></li>
 281      <li><a href="#examples-documentcloud">DocumentCloud</a></li>
 282      <li><a href="#examples-linkedin">LinkedIn Mobile</a></li>
 283      <li><a href="#examples-flow">Flow</a></li>
 284      <li><a href="#examples-audiovroom">AudioVroom</a></li>
 285      <li><a href="#examples-foursquare">Foursquare</a></li>
 286      <li><a href="#examples-do">Do</a></li>
 287      <li><a href="#examples-posterous">Posterous Spaces</a></li>
 288      <li><a href="#examples-groupon">Groupon Now!</a></li>
 289      <li><a href="#examples-basecamp">Basecamp Mobile</a></li>
 290      <li><a href="#examples-slavery-footprint">Slavery Footprint</a></li>
 291      <li><a href="#examples-diaspora">Diaspora</a></li>
 292      <li><a href="#examples-trajectory">Trajectory</a></li>
 293      <li><a href="#examples-soundcloud">SoundCloud Mobile</a></li>
 294      <li><a href="#examples-pandora">Pandora</a></li>
 295      <li><a href="#examples-cloudapp">CloudApp</a></li>
 296      <li><a href="#examples-seatgeek">SeatGeek</a></li>
 297      <li><a href="#examples-grove">Grove.io</a></li>
 298      <li><a href="#examples-kicksend">Kicksend</a></li>
 299      <li><a href="#examples-shortmail">Shortmail</a></li>
 300      <li><a href="#examples-battlefield">Battlefield Play4Free</a></li>
 301      <li><a href="#examples-salon">Salon.io</a></li>
 302      <li><a href="#examples-quoteroller">Quote Roller</a></li>
 303      <li><a href="#examples-tilemill">TileMill</a></li>
 304      <li><a href="#examples-rround">rround.me</a></li>
 305      <li>- <a href="#examples-blossom">Blossom</a></li>
 306      <li>- <a href="#examples-instagreat">Insta-great!</a></li>
 307      <li>- <a href="#examples-decide">Decide</a></li>
 308      <li>- <a href="#examples-trello">Trello</a></li>
 309      <li>- <a href="#examples-bittorrent">BitTorrent</a></li>
 310      <li>- <a href="#examples-picplum">Picplum</a></li>
 311      <li>- <a href="#examples-ducksboard">Ducksboard</a></li>
 312      <li>- <a href="#examples-quietwrite">QuietWrite</a></li>
 313      <li>- <a href="#examples-tzigla">Tzigla</a></li>
 314    </ul>
 315
 316    <a class="toc_title" href="#faq">
 317      F.A.Q.
 318    </a>
 319    <ul class="toc_section">
 320      <li><a href="#FAQ-events">Catalog of Events</a></li>
 321      <li><a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
 322      <li><a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
 323      <li><a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
 324      <li><a href="#FAQ-mvc">Traditional MVC</a></li>
 325      <li><a href="#FAQ-this">Binding "this"</a></li>
 326    </ul>
 327
 328    <a class="toc_title" href="#changelog">
 329      Change Log
 330    </a>
 331
 332  </div>
 333
 334  <div class="container">
 335
 336    <p>
 337      <img style="width: 451px; height: 80px;" src="docs/images/backbone.png" alt="Backbone.js" />
 338    </p>
 339
 340    <p>
 341      <a href="http://github.com/documentcloud/backbone/">Backbone</a>
 342      supplies structure to JavaScript-heavy applications by providing <b>models</b> with
 343      key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
 344      <b>views</b> with declarative event handling, and connects it all to your
 345      existing application over a RESTful JSON interface.
 346    </p>
 347
 348    <p>
 349      The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
 350      and the <a href="docs/backbone.html">annotated source code</a> is available,
 351      as well as an online <a href="test/test.html">test suite</a>, an
 352      <a href="examples/todos/index.html">example application</a> and a
 353      <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>.
 354    </p>
 355
 356    <p>
 357      You can report bugs and discuss features on the
 358      <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
 359      on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
 360      <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
 361      or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
 362    </p>
 363
 364    <p>
 365      <i>
 366        Backbone is an open-source component of
 367        <a href="http://documentcloud.org/">DocumentCloud</a>.
 368      </i>
 369    </p>
 370
 371    <h2 id="downloads">
 372      Downloads &amp; Dependencies
 373      <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
 374    </h2>
 375
 376    <table>
 377      <tr>
 378        <td><a href="backbone.js">Development Version (0.5.3)</a></td>
 379        <td><i>41kb, Full Source with Comments</i></td>
 380      </tr>
 381      <tr>
 382        <td><a href="backbone-min.js">Production Version (0.5.3)</a></td>
 383        <td><i>4.6kb, Packed and Gzipped</i></td>
 384      </tr>
 385    </table>
 386
 387    <p>
 388      Backbone's only hard dependency is
 389      <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
 390      For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
 391      and DOM manipulation with <a href="#View">Backbone.View</a>, include
 392      <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
 393      <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or
 394      <a href="http://zeptojs.com/">Zepto</a>.
 395    </p>
 396
 397    <h2 id="Introduction">Introduction</h2>
 398
 399    <p>
 400      When working on a web application that involves a lot of JavaScript, one
 401      of the first things you learn is to stop tying your data to the DOM. It's all
 402      too easy to create JavaScript applications that end up as tangled piles of
 403      jQuery selectors and callbacks, all trying frantically to keep data in
 404      sync between the HTML UI, your JavaScript logic, and the database on your
 405      server. For rich client-side applications, a more structured approach
 406      is often helpful.
 407    </p>
 408
 409    <p>
 410      With Backbone, you represent your data as
 411      <a href="#Model">Models</a>, which can be created, validated, destroyed,
 412      and saved to the server. Whenever a UI action causes an attribute of
 413      a model to change, the model triggers a <i>"change"</i> event; all
 414      the <a href="#View">Views</a> that display the model's state can be notified of the
 415      change, so that they are able to respond accordingly, re-rendering themselves with
 416      the new information. In a finished Backbone app, you don't have to write the glue
 417      code that looks into the DOM to find an element with a specific <i>id</i>,
 418      and update the HTML manually
 419      &mdash; when the model changes, the views simply update themselves.
 420    </p>
 421
 422    <p>
 423      Many of the examples that follow are runnable. Click the <i>play</i> button
 424      to execute them.
 425    </p>
 426
 427    <h2 id="Events">Backbone.Events</h2>
 428
 429    <p>
 430      <b>Events</b> is a module that can be mixed in to any object, giving the
 431      object the ability to bind and trigger custom named events. Events do not
 432      have to be declared before they are bound, and may take passed arguments.
 433      For example:
 434    </p>
 435
 436<pre class="runnable">
 437var object = {};
 438
 439_.extend(object, Backbone.Events);
 440
 441object.bind("alert", function(msg) {
 442  alert("Triggered " + msg);
 443});
 444
 445object.trigger("alert", "an event");
 446</pre>
 447
 448    <p id="Events-bind">
 449      <b class="header">bind</b><code>object.bind(event, callback, [context])</code>
 450      <br />
 451      Bind a <b>callback</b> function to an object. The callback will be invoked
 452      whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
 453      If you have a large number of different events on a page, the convention is to use colons to
 454      namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
 455    </p>
 456
 457    <p>
 458      To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
 459      pass the optional third argument: <tt>model.bind('change', this.render, this)</tt>
 460    </p>
 461
 462    <p>
 463      Callbacks bound to the special
 464      <tt>"all"</tt> event will be triggered when any event occurs, and are passed
 465      the name of the event as the first argument. For example, to proxy all events
 466      from one object to another:
 467    </p>
 468
 469<pre>
 470proxy.bind("all", function(eventName) {
 471  object.trigger(eventName);
 472});
 473</pre>
 474
 475    <p id="Events-unbind">
 476      <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
 477      <br />
 478      Remove a previously-bound <b>callback</b> function from an object. If no
 479      callback is specified, all callbacks for the <b>event</b> will be
 480      removed. If no event is specified, <i>all</i> event callbacks on the object
 481      will be removed.
 482    </p>
 483
 484<pre>
 485object.unbind("change", onChange);  // Removes just the onChange callback.
 486
 487object.unbind("change");            // Removes all "change" callbacks.
 488
 489object.unbind();                    // Removes all callbacks on object.
 490</pre>
 491
 492    <p id="Events-trigger">
 493      <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
 494      <br />
 495      Trigger callbacks for the given <b>event</b>. Subsequent arguments to
 496      <b>trigger</b> will be passed along to the event callbacks.
 497    </p>
 498
 499    <h2 id="Model">Backbone.Model</h2>
 500
 501    <p>
 502      <b>Models</b> are the heart of any JavaScript application, containing
 503      the interactive data as well as a large part of the logic surrounding it:
 504      conversions, validations, computed properties, and access control. You
 505      extend <b>Backbone.Model</b> with your domain-specific methods, and
 506      <b>Model</b> provides a basic set of functionality for managing changes.
 507    </p>
 508
 509    <p>
 510      The following is a contrived example, but it demonstrates defining a model
 511      with a custom method, setting an attribute, and firing an event keyed
 512      to changes in that specific attribute.
 513      After running this code once, <tt>sidebar</tt> will be
 514      available in your browser's console, so you can play around with it.
 515    </p>
 516
 517<pre class="runnable">
 518var Sidebar = Backbone.Model.extend({
 519  promptColor: function() {
 520    var cssColor = prompt("Please enter a CSS color:");
 521    this.set({color: cssColor});
 522  }
 523});
 524
 525window.sidebar = new Sidebar;
 526
 527sidebar.bind('change:color', function(model, color) {
 528  $('#sidebar').css({background: color});
 529});
 530
 531sidebar.set({color: 'white'});
 532
 533sidebar.promptColor();
 534</pre>
 535
 536    <p id="Model-extend">
 537      <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
 538      <br />
 539      To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
 540      and provide instance <b>properties</b>, as well as optional
 541      <b>classProperties</b> to be attached directly to the constructor function.
 542    </p>
 543
 544    <p>
 545      <b>extend</b> correctly sets up the prototype chain, so subclasses created
 546      with <b>extend</b> can be further extended and subclassed as far as you like.
 547    </p>
 548
 549<pre>
 550var Note = Backbone.Model.extend({
 551
 552  initialize: function() { ... },
 553
 554  author: function() { ... },
 555
 556  coordinates: function() { ... },
 557
 558  allowedToEdit: function(account) {
 559    return true;
 560  }
 561
 562});
 563
 564var PrivateNote = Note.extend({
 565
 566  allowedToEdit: function(account) {
 567    return account.owns(this);
 568  }
 569
 570});
 571</pre>
 572
 573    <p class="warning">
 574        Brief aside on <tt>super</tt>: JavaScript does not provide
 575        a simple way to call super &mdash; the function of the same name defined
 576        higher on the prototype chain. If you override a core function like
 577        <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
 578        parent object's implementation, you'll have to explicitly call it, along these lines:
 579    </p>
 580
 581<pre>
 582var Note = Backbone.Model.extend({
 583  set: function(attributes, options) {
 584    Backbone.Model.prototype.set.call(this, attributes, options);
 585    ...
 586  }
 587});
 588</pre>
 589
 590    <p id="Model-constructor">
 591      <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
 592      <br />
 593      When creating an instance of a model, you can pass in the initial values
 594      of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
 595      model. If you define an <b>initialize</b> function, it will be invoked when
 596      the model is created.
 597    </p>
 598
 599<pre>
 600new Book({
 601  title: "One Thousand and One Nights",
 602  author: "Scheherazade"
 603});
 604</pre>
 605
 606    <p id="Model-get">
 607      <b class="header">get</b><code>model.get(attribute)</code>
 608      <br />
 609      Get the current value of an attribute from the model. For example:
 610      <tt>note.get("title")</tt>
 611    </p>
 612
 613    <p id="Model-set">
 614      <b class="header">set</b><code>model.set(attributes, [options])</code>
 615      <br />
 616      Set a hash of attributes (one or many) on the model. If any of the attributes
 617      change the models state, a <tt>"change"</tt> event will be triggered, unless
 618      <tt>{silent: true}</tt> is passed as an option. Change events for specific
 619      attributes are also triggered, and you can bind to those as well, for example:
 620      <tt>change:title</tt>, and <tt>change:content</tt>.
 621    </p>
 622
 623<pre>
 624note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
 625</pre>
 626
 627    <p>
 628      If the model has a <a href="#Model-validate">validate</a> method,
 629      it will be validated before the attributes are set, no changes will
 630      occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
 631      Otherwise, <b>set</b> returns a reference to the model.
 632      You may also pass an <tt>error</tt>
 633      callback in the options, which will be invoked instead of triggering an
 634      <tt>"error"</tt> event, should validation fail.
 635    </p>
 636
 637    <p id="Model-escape">
 638      <b class="header">escape</b><code>model.escape(attribute)</code>
 639      <br />
 640      Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
 641      of a model's attribute. If you're interpolating data from the model into
 642      HTML, using <b>escape</b> to retrieve attributes will prevent
 643      <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
 644    </p>
 645
 646<pre class="runnable">
 647var hacker = new Backbone.Model({
 648  name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
 649});
 650
 651alert(hacker.escape('name'));
 652</pre>
 653
 654    <p id="Model-has">
 655      <b class="header">has</b><code>model.has(attribute)</code>
 656      <br />
 657      Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
 658      value.
 659    </p>
 660
 661<pre>
 662if (note.has("title")) {
 663  ...
 664}
 665</pre>
 666
 667    <p id="Model-unset">
 668      <b class="header">unset</b><code>model.unset(attribute, [options])</code>
 669      <br />
 670      Remove an attribute by deleting it from the internal attributes hash.
 671      Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
 672    </p>
 673
 674    <p id="Model-clear">
 675      <b class="header">clear</b><code>model.clear([options])</code>
 676      <br />
 677      Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
 678      <tt>silent</tt> is passed as an option.
 679    </p>
 680
 681    <p id="Model-id">
 682      <b class="header">id</b><code>model.id</code>
 683      <br />
 684      A special property of models, the <b>id</b> is an arbitrary string
 685      (integer id or UUID). If you set the <b>id</b> in the
 686      attributes hash, it will be copied onto the model as a direct property.
 687      Models can be retrieved by id from collections, and the id is used to generate
 688      model URLs by default.
 689    </p>
 690
 691    <p id="Model-idAttribute">
 692      <b class="header">idAttribute</b><code>model.idAttribute</code>
 693      <br />
 694      A model's unique identifier is stored under the <tt>id</tt> attribute.
 695      If you're directly communicating with a backend (CouchDB, MongoDB) that uses
 696      a different unique key, you may set a Model's <tt>idAttribute</tt> to
 697      transparently map from that key to <tt>id</tt>.
 698
 699<pre class="runnable">
 700var Meal = Backbone.Model.extend({
 701  idAttribute: "_id"
 702});
 703
 704var cake = new Meal({ _id: 1, name: "Cake" });
 705alert("Cake id: " + cake.id);
 706</pre>
 707    </p>
 708
 709    <p id="Model-cid">
 710      <b class="header">cid</b><code>model.cid</code>
 711      <br />
 712      A special property of models, the <b>cid</b> or client id is a unique identifier
 713      automatically assigned to all models when they're first created. Client ids
 714      are handy when the model has not yet been saved to the server, and does not
 715      yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
 716      Client ids take the form: <tt>c1, c2, c3 ...</tt>
 717    </p>
 718
 719    <p id="Model-attributes">
 720      <b class="header">attributes</b><code>model.attributes</code>
 721      <br />
 722      The <b>attributes</b> property is the internal hash containing the model's
 723      state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
 724      them directly. If you'd like to retrieve and munge a copy of the model's
 725      attributes, use <a href="#Model-toJSON">toJSON</a> instead.
 726    </p>
 727
 728    <p id="Model-defaults">
 729      <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
 730      <br />
 731      The <b>defaults</b> hash (or function) can be used to specify the default
 732      attributes for your model. When creating an instance of the model,
 733      any unspecified attributes will be set to their default value.
 734    </p>
 735
 736<pre class="runnable">
 737var Meal = Backbone.Model.extend({
 738  defaults: {
 739    "appetizer":  "caesar salad",
 740    "entree":     "ravioli",
 741    "dessert":    "cheesecake"
 742  }
 743});
 744
 745alert("Dessert will be " + (new Meal).get('dessert'));
 746</pre>
 747
 748    <p class="warning">
 749      Remember that in JavaScript, objects are passed by reference, so if you
 750      include an object as a default value, it will be shared among all instances.
 751    </p>
 752
 753    <p id="Model-toJSON">
 754      <b class="header">toJSON</b><code>model.toJSON()</code>
 755      <br />
 756      Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
 757      This can be used for persistence, serialization, or for augmentation before
 758      being handed off to a view. The name of this method is a bit confusing, as
 759      it doesn't actually return a JSON string &mdash; but I'm afraid that it's
 760      the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
 761    </p>
 762
 763<pre class="runnable">
 764var artist = new Backbone.Model({
 765  firstName: "Wassily",
 766  lastName: "Kandinsky"
 767});
 768
 769artist.set({birthday: "December 16, 1866"});
 770
 771alert(JSON.stringify(artist));
 772</pre>
 773
 774    <p id="Model-fetch">
 775      <b class="header">fetch</b><code>model.fetch([options])</code>
 776      <br />
 777      Resets the model's state from the server. Useful if the model has never
 778      been populated with data, or if you'd like to ensure that you have the
 779      latest server state. A <tt>"change"</tt> event will be triggered if the
 780      server's state differs from the current attributes. Accepts
 781      <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
 782      are passed <tt>(model, response)</tt> as arguments.
 783    </p>
 784
 785<pre>
 786// Poll every 10 seconds to keep the channel model up-to-date.
 787setInterval(function() {
 788  channel.fetch();
 789}, 10000);
 790</pre>
 791
 792    <p id="Model-save">
 793      <b class="header">save</b><code>model.save([attributes], [options])</code>
 794      <br />
 795      Save a model to your database (or alternative persistence layer),
 796      by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
 797      hash (as in <a href="#Model-set">set</a>) should contain the attributes
 798      you'd like to change -- keys that aren't mentioned won't be altered.
 799      If the model has a <a href="#Model-validate">validate</a>
 800      method, and validation fails, the model will not be saved. If the model
 801      <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
 802      (HTTP <tt>POST</tt>), if the model already
 803      exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
 804    </p>
 805
 806    <p>
 807      In the following example, notice how our overridden version
 808      of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
 809      the first time the model is saved and an <tt>"update"</tt>
 810      request the second time.
 811    </p>
 812
 813<pre class="runnable">
 814Backbone.sync = function(method, model) {
 815  alert(method + ": " + JSON.stringify(model));
 816  model.id = 1;
 817};
 818
 819var book = new Backbone.Model({
 820  title: "The Rough Riders",
 821  author: "Theodore Roosevelt"
 822});
 823
 824book.save();
 825
 826book.save({author: "Teddy"});
 827</pre>
 828
 829    <p>
 830      <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
 831      options hash, which are passed <tt>(model, response)</tt> as arguments.
 832      The <tt>error</tt> callback will also be invoked if the model has a
 833      <tt>validate</tt> method, and validation fails. If a server-side
 834      validation fails, return a non-<tt>200</tt> HTTP response code, along with
 835      an error response in text or JSON.
 836    </p>
 837
 838<pre>
 839book.save({author: "F.D.R."}, {error: function(){ ... }});
 840</pre>
 841
 842    <p id="Model-destroy">
 843      <b class="header">destroy</b><code>model.destroy([options])</code>
 844      <br />
 845      Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
 846      request to <a href="#Sync">Backbone.sync</a>. Accepts
 847      <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
 848      Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
 849      through any collections that contain it.
 850    </p>
 851
 852<pre>
 853book.destroy({success: function(model, response) {
 854  ...
 855}});
 856</pre>
 857
 858    <p id="Model-validate">
 859      <b class="header">validate</b><code>model.validate(attributes)</code>
 860      <br />
 861      This method is left undefined, and you're encouraged to override it with
 862      your custom validation logic, if you have any that can be performed
 863      in JavaScript. <b>validate</b> is called before <tt>set</tt> and
 864      <tt>save</tt>, and is passed the attributes that are about to be updated.
 865      If the model and attributes are valid, don't return anything from <b>validate</b>;
 866      if the attributes are invalid, return an error of your choosing. It
 867      can be as simple as a string error message to be displayed, or a complete
 868      error object that describes the error programmatically. <tt>set</tt> and
 869      <tt>save</tt> will not continue if <b>validate</b> returns an error.
 870      Failed validations trigger an <tt>"error"</tt> event.
 871    </p>
 872
 873<pre class="runnable">
 874var Chapter = Backbone.Model.extend({
 875  validate: function(attrs) {
 876    if (attrs.end < attrs.start) {
 877      return "can't end before it starts";
 878    }
 879  }
 880});
 881
 882var one = new Chapter({
 883  title : "Chapter One: The Beginning"
 884});
 885
 886one.bind("error", function(model, error) {
 887  alert(model.get("title") + " " + error);
 888});
 889
 890one.set({
 891  start: 15,
 892  end:   10
 893});
 894</pre>
 895
 896    <p>
 897      <tt>"error"</tt> events are useful for providing coarse-grained error
 898      messages at the model or collection level, but if you have a specific view
 899      that can better handle the error, you may override and suppress the event
 900      by passing an <tt>error</tt> callback directly:
 901    </p>
 902
 903<pre>
 904account.set({access: "unlimited"}, {
 905  error: function(model, error) {
 906    alert(error);
 907  }
 908});
 909</pre>
 910
 911    <p id="Model-url">
 912      <b class="header">url</b><code>model.url()</code>
 913      <br />
 914      Returns the relative URL where the model's resource would be located on
 915      the server. If your models are located somewhere else, override this method
 916      with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
 917      falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
 918    </p>
 919
 920    <p>
 921      Delegates to <a href="#Collection-url">Collection#url</a> to generate the
 922      URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
 923      property, if all models of this class share a common root URL.
 924      A model with an id of <tt>101</tt>, stored in a
 925      <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
 926      would have this URL: <tt>"/documents/7/notes/101"</tt>
 927    </p>
 928
 929    <p id="Model-urlRoot">
 930      <b class="header">urlRoot</b><code>model.urlRoot</code>
 931      <br />
 932      Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
 933      to enable the default <a href="#Model-url">url</a> function to generate
 934      URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
 935    </p>
 936
 937<pre class="runnable">
 938var Book = Backbone.Model.extend({urlRoot : '/books'});
 939
 940var solaris = new Book({id: "1083-lem-solaris"});
 941
 942alert(solaris.url());
 943</pre>
 944
 945    <p id="Model-parse">
 946      <b class="header">parse</b><code>model.parse(response)</code>
 947      <br />
 948      <b>parse</b> is called whenever a model's data is returned by the
 949      server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
 950      The function is passed the raw <tt>response</tt> object, and should return
 951      the attributes hash to be <a href="#Model-set">set</a> on the model. The
 952      default implementation is a no-op, simply passing through the JSON response.
 953      Override this if you need to work with a preexisting API, or better namespace
 954      your responses.
 955    </p>
 956
 957    <p>
 958      If you're working with a Rails backend, you'll notice that Rails' default
 959      <tt>to_json</tt> implementation includes a model's attributes under a
 960      namespace. To disable this behavior for seamless Backbone integration, set:
 961    </p>
 962
 963<pre>
 964ActiveRecord::Base.include_root_in_json = false
 965</pre>
 966
 967    <p id="Model-clone">
 968      <b class="header">clone</b><code>model.clone()</code>
 969      <br />
 970      Returns a new instance of the model with identical attributes.
 971    </p>
 972
 973    <p id="Model-isNew">
 974      <b class="header">isNew</b><code>model.isNew()</code>
 975      <br />
 976      Has this model been saved to the server yet? If the model does not yet have
 977      an <tt>id</tt>, it is considered to be new.
 978    </p>
 979
 980    <p id="Model-change">
 981      <b class="header">change</b><code>model.change()</code>
 982      <br />
 983      Manually trigger the <tt>"change"</tt> event.
 984      If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
 985      aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
 986      when you're all finished.
 987    </p>
 988
 989    <p id="Model-hasChanged">
 990      <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
 991      <br />
 992      Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
 993      is passed, returns <tt>true</tt> if that specific attribute has changed.
 994    </p>
 995
 996    <p class="warning">
 997      Note that this method, and the following change-related ones,
 998      are only useful during the course of a <tt>"change"</tt> event.
 999    </p>
1000
1001<pre>
1002book.bind("change", function() {
1003  if (book.hasChanged("title")) {
1004    ...
1005  }
1006});
1007</pre>
1008
1009    <p id="Model-changedAttributes">
1010      <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
1011      <br />
1012      Retrieve a hash of only the model's attributes that have changed. Optionally,
1013      an external <b>attributes</b> hash can be passed in, returning
1014      the attributes in that hash which differ from the model. This can be used
1015      to figure out which portions of a view should be updated, or what calls
1016      need to be made to sync the changes to the server.
1017    </p>
1018
1019    <p id="Model-previous">
1020      <b class="header">previous</b><code>model.previous(attribute)</code>
1021      <br />
1022      During a <tt>"change"</tt> event, this method can be used to get the
1023      previous value of a changed attribute.
1024    </p>
1025
1026<pre class="runnable">
1027var bill = new Backbone.Model({
1028  name: "Bill Smith"
1029});
1030
1031bill.bind("change:name", function(model, name) {
1032  alert("Changed name from " + bill.previous("name") + " to " + name);
1033});
1034
1035bill.set({name : "Bill Jones"});
1036</pre>
1037
1038    <p id="Model-previousAttributes">
1039      <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
1040      <br />
1041      Return a copy of the model's previous attributes. Useful for getting a
1042      diff between versions of a model, or getting back to a valid state after
1043      an error occurs.
1044    </p>
1045
1046    <h2 id="Collection">Backbone.Collection</h2>
1047
1048    <p>
1049      Collections are ordered sets of models. You can bind <tt>"change"</tt> events
1050      to be notified when any model in the collection has been modified,
1051      listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
1052      the collection from the server, and use a full suite of
1053      <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
1054    </p>
1055
1056    <p>
1057      Any event that is triggered on a model in a collection will also be
1058      triggered on the collection directly, for convenience.
1059      This allows you to listen for changes to specific attributes in any
1060      model in a collection, for example:
1061      <tt>Documents.bind("change:selected", ...)</tt>
1062    </p>
1063
1064    <p id="Collection-extend">
1065      <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
1066      <br />
1067      To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
1068      providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
1069      directly to the collection's constructor function.
1070    </p>
1071
1072    <p id="Collection-model">
1073      <b class="header">model</b><code>collection.model</code>
1074      <br />
1075      Override this property to specify the model class that the collection
1076      contains. If defined, you can pass raw attributes objects (and arrays) to
1077      <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
1078      and <a href="#Collection-reset">reset</a>, and the attributes will be
1079      converted into a model of the proper type.
1080    </p>
1081
1082<pre>
1083var Library = Backbone.Collection.extend({
1084  model: Book
1085});
1086</pre>
1087
1088    <p id="Collection-constructor">
1089      <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
1090      <br />
1091      When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
1092      The collection's <a href="#Collection-comparator">comparator</a> function
1093      may be included as an option. If you define an <b>initialize</b> function, it will be
1094      invoked when the collection is created.
1095    </p>
1096
1097<pre>
1098var tabs = new TabSet([tab1, tab2, tab3]);
1099</pre>
1100
1101    <p id="Collection-models">
1102      <b class="header">models</b><code>collection.models</code>
1103      <br />
1104      Raw access to the JavaScript array of models inside of the collection. Usually you'll
1105      want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
1106      to access model objects, but occasionally a direct reference to the array
1107      is desired.
1108    </p>
1109
1110    <p id="Collection-toJSON">
1111      <b class="header">toJSON</b><code>collection.toJSON()</code>
1112      <br />
1113      Return an array containing the attributes hash of each model in the
1114      collection. This can be used to serialize and persist the
1115      collection as a whole. The name of this method is a bit confusing, because
1116      it conforms to
1117      <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
1118    </p>
1119
1120<pre class="runnable">
1121var collection = new Backbone.Collection([
1122  {name: "Tim", age: 5},
1123  {name: "Ida", age: 26},
1124  {name: "Rob", age: 55}
1125]);
1126
1127alert(JSON.stringify(collection));
1128</pre>
1129
1130    <p id="Collection-Underscore-Methods">
1131      <b class="header">Underscore Methods (26)</b>
1132      <br />
1133      Backbone proxies to <b>Underscore.js</b> to provide 26 iteration functions
1134      on <b>Backbone.Collection</b>. They aren't all documented here, but
1135      you can take a look at the Underscore documentation for the full details&hellip;
1136    </p>
1137
1138    <ul>
1139      <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
1140      <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
1141      <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
1142      <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
1143      <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
1144      <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
1145      <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
1146      <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
1147      <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
1148      <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
1149      <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
1150      <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
1151      <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
1152      <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
1153      <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li>
1154      <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
1155      <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
1156      <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
1157      <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
1158      <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
1159      <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
1160      <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
1161      <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
1162      <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
1163      <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
1164      <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
1165    </ul>
1166
1167<pre>
1168Books.each(function(book) {
1169  book.publish();
1170});
1171
1172var titles = Books.map(function(book) {
1173  return book.get("title");
1174});
1175
1176var publishedBooks = Books.filter(function(book) {
1177  return book.get("published") === true;
1178});
1179
1180var alphabetical = Books.sortBy(function(book) {
1181  return book.author.get("name").toLowerCase();
1182});
1183</pre>
1184
1185    <p id="Collection-add">
1186      <b class="header">add</b><code>collection.add(models, [options])</code>
1187      <br />
1188      Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
1189      event, which you can pass <tt>{silent: true}</tt> to suppress. If a
1190      <a href="#Collection-model">model</a> property is defined, you may also pass
1191      raw attributes objects, and have them be vivified as instances of the model.
1192      Pass <tt>{at: index}</tt> to splice the model into the collection at the
1193      specified <tt>index</tt>.
1194    </p>
1195
1196<pre class="runnable">
1197var ships = new Backbone.Collection;
1198
1199ships.bind("add", function(ship) {
1200  alert("Ahoy " + ship.get("name") + "!");
1201});
1202
1203ships.add([
1204  {name: "Flying Dutchman"},
1205  {name: "Black Pearl"}
1206]);
1207</pre>
1208
1209    <p id="Collection-remove">
1210      <b class="header">remove</b><code>collection.remove(models, [options])</code>
1211      <br />
1212      Remove a model (or an array of models) from the collection. Fires a
1213      <tt>"remove"</tt> event, which you can use <tt>silent</tt>
1214      to suppress.
1215    </p>
1216
1217    <p id="Collection-get">
1218      <b class="header">get</b><code>collection.get(id)</code>
1219      <br />
1220      Get a model from a collection, specified by <b>id</b>.
1221    </p>
1222
1223<pre>
1224var book = Library.get(110);
1225</pre>
1226
1227    <p id="Collection-getByCid">
1228      <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
1229      <br />
1230      Get a model from a collection, specified by client id. The client id
1231      is the <tt>.cid</tt> property of the model, automatically assigned whenever
1232      a model is created. Useful for models which have not yet been saved to
1233      the server, and do not yet have true ids.
1234    </p>
1235
1236    <p id="Collection-at">
1237      <b class="header">at</b><code>collection.at(index)</code>
1238      <br />
1239      Get a model from a collection, specified by index. Useful if your collection
1240      is sorted, and if your collection isn't sorted, <b>at</b> will still
1241      retrieve models in insertion order.
1242    </p>
1243
1244    <p id="Collection-length">
1245      <b class="header">length</b><code>collection.length</code>
1246      <br />
1247      Like an array, a Collection maintains a <tt>length</tt> property, counting
1248      the number of models it contains.
1249    </p>
1250
1251    <p id="Collection-comparator">
1252      <b class="header">comparator</b><code>collection.comparator</code>
1253      <br />
1254      By default there is no <b>comparator</b> function on a collection.
1255      If you define a comparator, it will be used to maintain
1256      the collection in sorted order. This means that as models are added,
1257      they are inserted at the correct index in <tt>collection.models</tt>.
1258      Comparator functions take a model and return a numeric or string value
1259      by which the model should be ordered relative to others.
1260    </p>
1261
1262    <p>
1263      Note how even though all of the chapters in this example are added backwards,
1264      they come out in the proper order:
1265    </p>
1266
1267<pre class="runnable">
1268var Chapter  = Backbone.Model;
1269var chapters = new Backbone.Collection;
1270
1271chapters.comparator = function(chapter) {
1272  return chapter.get("page");
1273};
1274
1275chapters.add(new Chapter({page: 9, title: "The End"}));
1276chapters.add(new Chapter({page: 5, title: "The Middle"}));
1277chapters.add(new Chapter({page: 1, title: "The Beginning"}));
1278
1279alert(chapters.pluck('title'));
1280</pre>
1281
1282    <p class="warning">
1283      Brief aside: This comparator function is different than JavaScript's regular
1284      "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
1285      and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
1286    </p>
1287
1288    <p class="warning">
1289      Collections with comparator functions will not automatically re-sort if you
1290      later change model attributes, so you may wish to call <tt>sort</tt> after
1291      changing model attributes that would affect the order.
1292    </p>
1293
1294    <p id="Collection-sort">
1295      <b class="header">sort</b><code>collection.sort([options])</code>
1296      <br />
1297      Force a collection to re-sort itself. You don't need to call this under
1298      normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
1299      will maintain itself in proper sort order at all times. Calling <b>sort</b>
1300      triggers the collection's <tt>"reset"</tt> event, unless silenced by passing
1301      <tt>{silent: true}</tt>
1302    </p>
1303
1304    <p id="Collection-pluck">
1305      <b class="header">pluck</b><code>collection.pluck(attribute)</code>
1306      <br />
1307      Pluck an attribute from each model in the collection. Equivalent to calling
1308      <tt>map</tt>, and returning a single attribute from the iterator.
1309    </p>
1310
1311<pre class="runnable">
1312var stooges = new Backbone.Collection([
1313  new Backbone.Model({name: "Curly"}),
1314  new Backbone.Model({name: "Larry"}),
1315  new Backbone.Model({name: "Moe"})
1316]);
1317
1318var names = stooges.pluck("name");
1319
1320alert(JSON.stringify(names));
1321</pre>
1322
1323    <p id="Collection-url">
1324      <b class="header">url</b><code>collection.url or collection.url()</code>
1325      <br />
1326      Set the <b>url</b> property (or function) on a collection to reference
1327      its location on the server. Models within the collection will use <b>url</b>
1328      to construct URLs of their own.
1329    </p>
1330
1331<pre>
1332var Notes = Backbone.Collection.extend({
1333  url: '/notes'
1334});
1335
1336// Or, something more sophisticated:
1337
1338var Notes = Backbone.Collection.extend({
1339  url: function() {
1340    return this.document.url() + '/notes';
1341  }
1342});
1343</pre>
1344
1345    <p id="Collection-parse">
1346      <b class="header">parse</b><code>collection.parse(response)</code>
1347      <br />
1348      <b>parse</b> is called by Backbone whenever a collection's models are
1349      returned by the server, in <a href="#Collection-fetch">fetch</a>.
1350      The function is passed the raw <tt>response</tt> object, and should return
1351      the array of model attributes to be <a href="#Collection-add">added</a>
1352      to the collection. The default implementation is a no-op, simply passing
1353      through the JSON response. Override this if you need to work with a
1354      preexisting API, or better namespace your responses.
1355    </p>
1356
1357<pre>
1358var Tweets = Backbone.Collection.extend({
1359  // The Twitter Search API returns tweets under "results".
1360  parse: function(response) {
1361    return response.results;
1362  }
1363});
1364</pre>
1365
1366    <p id="Collection-fetch">
1367      <b class="header">fetch</b><code>collection.fetch([options])</code>
1368      <br />
1369      Fetch the default set of models for this collection from the server,
1370      resetting the collection when they arrive. The <b>options</b> hash takes
1371      <tt>success</tt> and <tt>error</tt>
1372      callbacks which will be passed <tt>(collec…

Large files files are truncated, but you can click here to view the full file