PageRenderTime 85ms CodeModel.GetById 4ms app.highlight 67ms RepoModel.GetById 2ms app.codeStats 0ms

/index.html

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

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