PageRenderTime 113ms CodeModel.GetById 63ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 1ms

/node_modules/backbone/index.html

https://bitbucket.org/moonboots/backbone-everywhere
HTML | 2863 lines | 2452 code | 411 blank | 0 comment | 0 complexity | e2ef212d72b73e214a25274be3ba5dc3 MD5 | raw file

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

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