PageRenderTime 53ms CodeModel.GetById 4ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

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

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