<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <title>Backbone.js</title>
  <style>
    body {
      font-size: 14px;
      line-height: 22px;
      font-family: Helvetica Neue, Helvetica, Arial;
      background: #f4f4f4 url(docs/images/background.png);
    }
    .interface {
      font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
    }
    div#sidebar {
      background: #fff;
      position: fixed;
      top: 0; left: 0; bottom: 0;
      width: 200px;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 15px 0 30px 30px;
      border-right: 1px solid #ddd;
      box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
    }
      a.toc_title, a.toc_title:visited {
        display: block;
        color: black;
        font-weight: bold;
        margin-top: 15px;
      }
        div.toc_title:hover {
          text-decoration: underline;
        }
        #sidebar .version {
          font-size: 10px;
          font-weight: normal;
        }
      ul.toc_section {
        font-size: 11px;
        line-height: 14px;
        margin: 5px 0 0 0;
        padding-left: 0px;
        list-style-type: none;
        font-family: Lucida Grande;
      }
        .toc_section li {
          cursor: pointer;
          margin: 0 0 3px 0;
        }
          .toc_section li a {
            color: black;
          }
    div.container {
      position: relative;
      width: 550px;
      margin: 40px 0 50px 260px;
    }
    div.run {
      position: absolute;
      right: 15px;
      width: 26px; height: 18px;
      background: url('docs/images/arrows.png') no-repeat -26px 0;
    }
      div.run:active {
        background-position: -51px 0;
      }
    p, div.container ul {
      margin: 20px 0;
      width: 550px;
    }
      p.warning {
        font-size: 12px;
        line-height: 18px;
        font-style: italic;
      }
      div.container ul {
        list-style: circle;
        font-size: 12px;
        padding-left: 15px;
      }
    a, a:visited {
      color: #444;
      text-decoration: none;
    }
    a:active, a:hover {
      color: #000;
      text-decoration: underline;
    }
    a img {
      border: 0;
    }
    h1, h2, h3, h4, h5, h6 {
      padding-top: 20px;
    }
      h2 {
        font-size: 20px;
      }
    b.header {
      font-size: 16px;
      line-height: 30px;
    }
    span.alias {
      font-size: 14px;
      font-style: italic;
      margin-left: 20px;
    }
    table {
      margin: 15px 0 0; padding: 0;
    }
      tr, td {
        margin: 0; padding: 0;
      }
        td {
          padding: 0px 15px 5px 0;
        }
    code, pre, tt {
      font-family: Monaco, Consolas, "Lucida Console", monospace;
      font-size: 12px;
      line-height: 18px;
      font-style: normal;
    }
      tt {
        padding: 0px 3px;
        background: #fff;
        border: 1px solid #ddd;
        zoom: 1;
      }
      code {
        margin-left: 20px;
      }
      pre {
        font-size: 12px;
        padding: 2px 0 2px 15px;
        border: 4px solid #bbb; border-top: 0; border-bottom: 0;
        margin: 0px 0 30px;
      }
  </style>
</head>
<body>

  <div id="sidebar" class="interface">

    <a class="toc_title" href="#">
      Backbone.js <span class="version">(0.3.3)</span>
    </a>

    <a class="toc_title" href="#Introduction">
      Introduction
    </a>

    <a class="toc_title" href="#Events">
      Events
    </a>
    <ul class="toc_section">
      <li>– <a href="#Events-bind">bind</a></li>
      <li>– <a href="#Events-unbind">unbind</a></li>
      <li>– <a href="#Events-trigger">trigger</a></li>
    </ul>

    <a class="toc_title" href="#Model">
      Model
    </a>
    <ul class="toc_section">
      <li>– <a href="#Model-extend">extend</a></li>
      <li>– <a href="#Model-constructor">constructor / initialize</a></li>
      <li>– <a href="#Model-get">get</a></li>
      <li>– <a href="#Model-escape">escape</a></li>
      <li>– <a href="#Model-set">set</a></li>
      <li>– <a href="#Model-unset">unset</a></li>
      <li>– <a href="#Model-clear">clear</a></li>
      <li>– <a href="#Model-id">id</a></li>
      <li>– <a href="#Model-cid">cid</a></li>
      <li>– <a href="#Model-attributes">attributes</a></li>
      <li>– <a href="#Model-defaults">defaults</a></li>
      <li>- <a href="#Model-toJSON">toJSON</a></li>
      <li>– <a href="#Model-fetch">fetch</a></li>
      <li>– <a href="#Model-save">save</a></li>
      <li>– <a href="#Model-destroy">destroy</a></li>
      <li>– <a href="#Model-validate">validate</a></li>
      <li>– <a href="#Model-url">url</a></li>
      <li>– <a href="#Model-parse">parse</a></li>
      <li>– <a href="#Model-clone">clone</a></li>
      <li>– <a href="#Model-isNew">isNew</a></li>
      <li>– <a href="#Model-change">change</a></li>
      <li>– <a href="#Model-hasChanged">hasChanged</a></li>
      <li>– <a href="#Model-changedAttributes">changedAttributes</a></li>
      <li>– <a href="#Model-previous">previous</a></li>
      <li>– <a href="#Model-previousAttributes">previousAttributes</a></li>
    </ul>

    <a class="toc_title" href="#Collection">
      Collection
    </a>
    <ul class="toc_section">
      <li>– <a href="#Collection-extend">extend</a></li>
      <li>– <a href="#Collection-model">model</a></li>
      <li>– <a href="#Collection-constructor">constructor / initialize</a></li>
      <li>– <a href="#Collection-models">models</a></li>
      <li>– <a href="#Collection-toJSON">toJSON</a></li>
      <li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (25)</b></a></li>
      <li>– <a href="#Collection-add">add</a></li>
      <li>– <a href="#Collection-remove">remove</a></li>
      <li>– <a href="#Collection-get">get</a></li>
      <li>– <a href="#Collection-getByCid">getByCid</a></li>
      <li>– <a href="#Collection-at">at</a></li>
      <li>– <a href="#Collection-length">length</a></li>
      <li>– <a href="#Collection-comparator">comparator</a></li>
      <li>– <a href="#Collection-sort">sort</a></li>
      <li>– <a href="#Collection-pluck">pluck</a></li>
      <li>– <a href="#Collection-url">url</a></li>
      <li>– <a href="#Collection-parse">parse</a></li>
      <li>– <a href="#Collection-fetch">fetch</a></li>
      <li>– <a href="#Collection-refresh">refresh</a></li>
      <li>– <a href="#Collection-create">create</a></li>
    </ul>

    <a class="toc_title" href="#Controller">
      Controller
    </a>
    <ul class="toc_section">
      <li>– <a href="#Controller-extend">extend</a></li>
      <li>– <a href="#Controller-routes">routes</a></li>
      <li>– <a href="#Controller-constructor">constructor / initialize</a></li>
      <li>– <a href="#Controller-route">route</a></li>
      <li>– <a href="#Controller-saveLocation">saveLocation</a></li>
    </ul>

    <a class="toc_title" href="#History">
      History
    </a>
    <ul class="toc_section">
      <li>– <a href="#History-start">start</a></li>
      <li>– <a href="#History-saveLocation">saveLocation</a></li>
    </ul>

    <a class="toc_title" href="#Sync">
      Sync
    </a>
    <ul class="toc_section">
      <li>– <a href="#Sync">Backbone.sync</a></li>
      <li>– <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
      <li>– <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
    </ul>

    <a class="toc_title" href="#View">
      View
    </a>
    <ul class="toc_section">
      <li>– <a href="#View-extend">extend</a></li>
      <li>– <a href="#View-constructor">constructor / initialize</a></li>
      <li>– <a href="#View-el">el</a></li>
      <li>– <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
      <li>– <a href="#View-render">render</a></li>
      <li>– <a href="#View-remove">remove</a></li>
      <li>– <a href="#View-make">make</a></li>
      <li>– <a href="#View-delegateEvents">delegateEvents</a></li>
    </ul>

    <a class="toc_title" href="#examples">
      Examples
    </a>

    <a class="toc_title" href="#changelog">
      Change Log
    </a>

  </div>

  <div class="container">

    <p>
      <img style="width: 385px; height: 126px;" src="docs/images/backbone.png" alt="Backbone.js" />
    </p>

    <p>
      <a href="http://github.com/documentcloud/backbone/">Backbone</a>
      supplies structure to JavaScript-heavy applications by providing <b>models</b> with
      key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
      <b>views</b> with declarative event handling, and connects it all to your
      existing application over a RESTful JSON interface.
    </p>

    <p>
      The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
      and the <a href="docs/backbone.html">annotated source code</a> is available,
      as well as an online <a href="test/test.html">test suite</a>, and
      <a href="examples/todos/index.html">example application</a>.
    </p>

    <p>
      You can report bugs and discuss features on the
      <a href="http://github.com/documentcloud/backbone/issues">issues page</a>,
      on Freenode in the <tt>#documentcloud</tt> channel,
      or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
    </p>

    <p>
      <i>
        Backbone is an open-source component of
        <a href="http://documentcloud.org/">DocumentCloud</a>.
      </i>
    </p>

    <h2 id="downloads">
      Downloads &amp; Dependencies
      <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
    </h2>

    <table>
      <tr>
        <td><a href="backbone.js">Development Version (0.3.3)</a></td>
        <td><i>35kb, Uncompressed with Comments</i></td>
      </tr>
      <tr>
        <td><a href="backbone-min.js">Production Version (0.3.3)</a></td>
        <td><i>3.9kb, Packed and Gzipped</i></td>
      </tr>
    </table>

    <p>
      Backbone's only hard dependency is
      <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
      For RESTful persistence, and DOM manipulation with
      <a href="#View">Backbone.View</a>,
      it's highly recommended to include
      <a href="http://www.json.org/json2.js">json2.js</a>, and either
      <a href="http://jquery.com">jQuery</a> or <a href="http://zeptojs.com/">Zepto</a>.
    </p>

    <h2 id="Introduction">Introduction</h2>

    <p>
      When working on a web application that involves a lot of JavaScript, one
      of the first things you learn is to stop tying your data to the DOM. It's all
      too easy to create JavaScript applications that end up as tangled piles of
      jQuery selectors and callbacks, all trying frantically to keep data in
      sync between the HTML UI, your JavaScript logic, and the database on your
      server. For rich client-side applications, a more structured approach
      is helpful.
    </p>

    <p>
      With Backbone, you represent your data as
      <a href="#Model">Models</a>, which can be created, validated, destroyed,
      and saved to the server. Whenever a UI action causes an attribute of
      a model to change, the model triggers a <i>"change"</i> event; all
      the <a href="#View">Views</a> that display the model's data are notified of the
      event, causing them to re-render. You don't have to write the glue
      code that looks into the DOM to find an element with a specific <i>id</i>,
      and update the HTML manually
      &mdash; when the model changes, the views simply update themselves.
    </p>

    <p>
      <i>How is this different than
        <a href="http://www.sproutcore.com/">SproutCore</a> or
        <a href="http://cappuccino.org/">Cappuccino</a>?
      </i>
    </p>

    <p>
      This question is frequently asked, and all three projects apply general
      <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
      principles to JavaScript applications. However, there isn't much basis
      for comparison. SproutCore and Cappuccino provide rich UI widgets, vast
      core libraries, and determine the structure of your HTML for you.
      Both frameworks measure in the hundreds of kilobytes when packed and
      gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser
      &mdash; there's a lot of room underneath for libraries of a more moderate scope.
      Backbone is a <i>4 kilobyte</i> include that provides
      just the core concepts of models, events, collections, views, controllers, 
      and persistence.
    </p>

    <p>
      Many of the examples that follow are runnable. Click the <i>play</i> button
      to execute them.
    </p>

    <h2 id="Events">Backbone.Events</h2>

    <p>
      <b>Events</b> is a module that can be mixed in to any object, giving the
      object the ability to bind and trigger custom named events. Events do not
      have to be declared before they are bound, and may take passed arguments.
      For example:
    </p>

<pre class="runnable">
var object = {};

_.extend(object, Backbone.Events);

object.bind("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");
</pre>

    <p id="Events-bind">
      <b class="header">bind</b><code>object.bind(event, callback)</code>
      <br />
      Bind a <b>callback</b> function to an object. The callback will be invoked
      whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
      If you have a large number of different events on a page, the convention is to use colons to
      namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
    </p>

    <p>
      Callbacks bound to the special
      <tt>"all"</tt> event will be triggered when any event occurs, and are passed
      the name of the event as the first argument. For example, to proxy all events
      from one object to another:
    </p>

<pre>
proxy.bind("all", function(eventName) {
  object.trigger(eventName);
});
</pre>

    <p id="Events-unbind">
      <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
      <br />
      Remove a previously-bound <b>callback</b> function from an object. If no
      callback is specified, all callbacks for the <b>event</b> will be
      removed. If no event is specified, <i>all</i> event callbacks on the object
      will be removed.
    </p>

<pre>
object.unbind("change", onChange);  // Removes just the onChange callback.

object.unbind("change");            // Removes all "change" callbacks.

object.unbind();                    // Removes all callbacks on object.
</pre>

    <p id="Events-trigger">
      <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
      <br />
      Trigger callbacks for the given <b>event</b>. Subsequent arguments to
      <b>trigger</b> will be passed along to the event callbacks.
    </p>

    <h2 id="Model">Backbone.Model</h2>

    <p>
      <b>Models</b> are the heart of any JavaScript application, containing
      the interactive data as well as a large part of the logic surrounding it:
      conversions, validations, computed properties, and access control. You
      extend <b>Backbone.Model</b> with your domain-specific methods, and
      <b>Model</b> provides a basic set of functionality for managing changes.
    </p>

    <p>
      The following is a contrived example, but it demonstrates defining a model
      with a custom method, setting an attribute, and firing an event keyed
      to changes in that specific attribute.
      After running this code once, <tt>sidebar</tt> will be
      available in your browser's console, so you can play around with it.
    </p>

<pre class="runnable">
var Sidebar = Backbone.Model.extend({
  promptColor: function() {
    var cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.bind('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();
</pre>

    <p id="Model-extend">
      <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
      <br />
      To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
      and provide instance <b>properties</b>, as well as optional
      <b>classProperties</b> to be attached directly to the constructor function.
    </p>

    <p>
      <b>extend</b> correctly sets up the prototype chain, so subclasses created
      with <b>extend</b> can be further extended and subclassed as far as you like.
    </p>

<pre>
var Note = Backbone.Model.extend({

  initialize: function() { ... },

  author: function() { ... },

  allowedToEdit: function(account) { ... },

  coordinates: function() { ... }

});
</pre>

    <p class="warning">
        Brief aside on <tt>super</tt>: JavaScript does not provide
        a simple way to call super &mdash; the function of the same name defined
        higher on the prototype chain. If you override a core function like
        <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
        parent object's implementation, you'll have to explicitly call it, along these lines:
    </p>

<pre>
var Note = Backbone.Model.extend({
  set: function(attributes, options) {
    Backbone.Model.prototype.set.call(this, attributes, options);
    ...
  }
});
</pre>

    <p id="Model-constructor">
      <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
      <br />
      When creating an instance of a model, you can pass in the initial values
      of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
      model. If you define an <b>initialize</b> function, it will be invoked when
      the model is created.
    </p>

<pre>
new Book({
  title: "One Thousand and One Nights",
  author: "Scheherazade"
});
</pre>

    <p id="Model-get">
      <b class="header">get</b><code>model.get(attribute)</code>
      <br />
      Get the current value of an attribute from the model. For example:
      <tt>note.get("title")</tt>
    </p>
    
    <p id="Model-escape">
      <b class="header">escape</b><code>model.escape(attribute)</code>
      <br />
      Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
      of a model's attribute. If you're interpolating data from the model into
      HTML, using <b>escape</b> to retrieve attributes will prevent 
      <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
    </p>
    
<pre class="runnable">
var hacker = new Backbone.Model({
  name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
});

alert(hacker.escape('name'));
</pre>

    <p id="Model-set">
      <b class="header">set</b><code>model.set(attributes, [options])</code>
      <br />
      Set a hash of attributes (one or many) on the model. If any of the attributes
      change the models state, a <tt>"change"</tt> event will be triggered, unless
      <tt>{silent: true}</tt> is passed as an option. Change events for specific
      attributes are also triggered, and you can bind to those as well, for example:
      <tt>change:title</tt>, and <tt>change:content</tt>.
    </p>

<pre>
note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
</pre>

    <p>
      If the model has a <a href="#Model-validate">validate</a> method,
      it will be validated before the attributes are set, no changes will
      occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
      You may also pass an <tt>error</tt>
      callback in the options, which will be invoked instead of triggering an
      <tt>"error"</tt> event, should validation fail.
    </p>

    <p id="Model-unset">
      <b class="header">unset</b><code>model.unset(attribute, [options])</code>
      <br />
      Remove an attribute by deleting it from the internal attributes hash.
      Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
    </p>

    <p id="Model-clear">
      <b class="header">clear</b><code>model.clear([options])</code>
      <br />
      Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
      <tt>silent</tt> is passed as an option.
    </p>

    <p id="Model-id">
      <b class="header">id</b><code>model.id</code>
      <br />
      A special property of models, the <b>id</b> is an arbitrary string
      (integer id or UUID). If you set the <b>id</b> in the
      attributes hash, it will be copied onto the model as a direct property.
      Models can be retrieved by id from collections, and the id is used to generate
      model URLs by default.
    </p>

    <p id="Model-cid">
      <b class="header">cid</b><code>model.cid</code>
      <br />
      A special property of models, the <b>cid</b> or client id is a unique identifier
      automatically assigned to all models when they're first created. Client ids
      are handy when the model has not yet been saved to the server, and does not
      yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
      Client ids take the form: <tt>c1, c2, c3 ...</tt>
    </p>

    <p id="Model-attributes">
      <b class="header">attributes</b><code>model.attributes</code>
      <br />
      The <b>attributes</b> property is the internal hash containing the model's
      state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
      them directly. If you'd like to retrieve and munge a copy of the model's
      attributes, use <a href="#Model-toJSON">toJSON</a> instead.
    </p>

    <p id="Model-defaults">
      <b class="header">defaults</b><code>model.defaults</code>
      <br />
      The <b>defaults</b> hash can be used to specify the default attributes
      for your model. When creating an instance of the model, any unspecified
      attributes will be set to their default value.
    </p>

<pre class="runnable">
var Meal = Backbone.Model.extend({
  defaults: {
    "appetizer":  "caesar salad",
    "entree":     "ravioli",
    "dessert":    "cheesecake"
  }
});

alert("Dessert will be " + (new Meal).get('dessert'));
</pre>

    <p id="Model-toJSON">
      <b class="header">toJSON</b><code>model.toJSON()</code>
      <br />
      Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
      This can be used for persistence, serialization, or for augmentation before
      being handed off to a view. The name of this method is a bit confusing, as
      it doesn't actually return a JSON string &mdash; but I'm afraid that it's
      the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
    </p>

<pre class="runnable">
var artist = new Backbone.Model({
  firstName: "Wassily",
  lastName: "Kandinsky"
});

artist.set({birthday: "December 16, 1866"});

alert(JSON.stringify(artist));
</pre>

    <p id="Model-fetch">
      <b class="header">fetch</b><code>model.fetch([options])</code>
      <br />
      Refreshes the model's state from the server. Useful if the model has never
      been populated with data, or if you'd like to ensure that you have the
      latest server state. A <tt>"change"</tt> event will be triggered if the
      server's state differs from the current attributes. Accepts
      <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
      are passed <tt>(model, response)</tt> as arguments.
    </p>

<pre>
// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
  channel.fetch();
}, 10000);
</pre>

    <p class="warning">
      <b>Cautionary Note:</b> When fetching or saving a model, make sure that the model is part of
      a collection with a <a href="#Collection-url">url</a> property specified,
      or that the model itself has a complete <a href="#Model-url">url</a> function
      of its own, so that the request knows where to go.
    </p>

    <p id="Model-save">
      <b class="header">save</b><code>model.save(attributes, [options])</code>
      <br />
      Save a model to your database (or alternative persistence layer),
      by delegating to <a href="#Sync">Backbone.sync</a>. If the model has a <a href="#Model-validate">validate</a>
      method, and validation fails, the model will not be saved. If the model
      <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
      (HTTP <tt>POST</tt>), if the model already
      exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>). Accepts
      <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
      are passed <tt>(model, response)</tt> as arguments. The <tt>error</tt> callback will
      also be invoked if the model has a <tt>validate</tt> method, and validation fails.
    </p>

    <p>
      In the following example, notice how because the model has never been
      saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
    </p>

<pre class="runnable">
Backbone.sync = function(method, model) {
  alert(method + ": " + JSON.stringify(model));
};

var book = new Backbone.Model({
  title: "The Rough Riders",
  author: "Theodore Roosevelt"
});

book.save();
</pre>

    <p id="Model-destroy">
      <b class="header">destroy</b><code>model.destroy([options])</code>
      <br />
      Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
      request to <a href="#Sync">Backbone.sync</a>. Accepts
      <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
    </p>

<pre>
book.destroy({success: function(model, response) {
  ...
}});
</pre>

    <p id="Model-validate">
      <b class="header">validate</b><code>model.validate(attributes)</code>
      <br />
      This method is left undefined, and you're encouraged to override it with
      your custom validation logic, if you have any that can be performed
      in JavaScript. <b>validate</b> is called before <tt>set</tt> and
      <tt>save</tt>, and is passed the attributes that are about to be updated.
      If the model and attributes are valid, don't return anything from <b>validate</b>;
      if the attributes are invalid, return an error of your choosing. It
      can be as simple as a string error message to be displayed, or a complete
      error object that describes the error programmatically. <tt>set</tt> and
      <tt>save</tt> will not continue if <b>validate</b> returns an error.
      Failed validations trigger an <tt>"error"</tt> event.
    </p>

<pre class="runnable">
var Chapter = Backbone.Model.extend({
  validate: function(attrs) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

one.bind("error", function(model, error) {
  alert(model.get("title") + " " + error);
});

one.set({
  start: 15,
  end:   10
});
</pre>

    <p>
      <tt>"error"</tt> events are useful for providing coarse-grained error
      messages at the model or collection level, but if you have a specific view
      that can better handle the error, you may override and suppress the event
      by passing an <tt>error</tt> callback directly:
    </p>

<pre>
account.set({access: "unlimited"}, {
  error: function(model, error) {
    alert(error);
  }
});
</pre>

    <p id="Model-url">
      <b class="header">url</b><code>model.url()</code>
      <br />
      Returns the relative URL where the model's resource would be located on
      the server. If your models are located somewhere else, override this method
      with the correct logic. Generates URLs of the form: <tt>"/[collection]/[id]"</tt>.
    </p>

    <p>
      Delegates to <a href="#Collection-url">Collection#url</a> to generate the
      URL, so make sure that you have it defined.
      A model with an id of <tt>101</tt>, stored in a
      <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/notes"</tt>,
      would have this URL: <tt>"/notes/101"</tt>
    </p>

    <p id="Model-parse">
      <b class="header">parse</b><code>model.parse(response)</code>
      <br />
      <b>parse</b> is called whenever a model's data is returned by the
      server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
      The function is passed the raw <tt>response</tt> object, and should return
      the attributes hash to be <a href="#Model-set">set</a> on the model. The
      default implementation is a no-op, simply passing through the JSON response.
      Override this if you need to work with a preexisting API, or better namespace
      your responses.
    </p>

    <p>
      If you're working with a Rails backend, you'll notice that Rails' default
      <tt>to_json</tt> implementation includes a model's attributes under a
      namespace. To disable this behavior for seamless Backbone integration, set:
    </p>

<pre>
ActiveRecord::Base.include_root_in_json = false
</pre>

    <p id="Model-clone">
      <b class="header">clone</b><code>model.clone()</code>
      <br />
      Returns a new instance of the model with identical attributes.
    </p>

    <p id="Model-isNew">
      <b class="header">isNew</b><code>model.isNew()</code>
      <br />
      Has this model been saved to the server yet? If the model does not yet have
      an <tt>id</tt>, it is considered to be new.
    </p>

    <p id="Model-change">
      <b class="header">change</b><code>model.change()</code>
      <br />
      Manually trigger the <tt>"change"</tt> event.
      If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
      aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
      when you're all finished.
    </p>

    <p id="Model-hasChanged">
      <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
      <br />
      Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
      is passed, returns <tt>true</tt> if that specific attribute has changed.
    </p>

<pre>
book.bind("change", function() {
  if (book.hasChanged("title")) {
    ...
  }
});
</pre>

    <p id="Model-changedAttributes">
      <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
      <br />
      Retrieve a hash of only the model's attributes that have changed. Optionally,
      an external <b>attributes</b> hash can be passed in, returning
      the attributes in that hash which differ from the model. This can be used
      to figure out which portions of a view should be updated, or what calls
      need to be made to sync the changes to the server.
    </p>

    <p id="Model-previous">
      <b class="header">previous</b><code>model.previous(attribute)</code>
      <br />
      During a <tt>"change"</tt> event, this method can be used to get the
      previous value of a changed attribute.
    </p>

<pre class="runnable">
var bill = new Backbone.Model({
  name: "Bill Smith"
});

bill.bind("change:name", function(model, name) {
  alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});
</pre>

    <p id="Model-previousAttributes">
      <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
      <br />
      Return a copy of the model's previous attributes. Useful for getting a
      diff between versions of a model, or getting back to a valid state after
      an error occurs.
    </p>

    <h2 id="Collection">Backbone.Collection</h2>

    <p>
      Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
      to be notified when any model in the collection has been modified,
      listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
      the collection from the server, and use a full suite of
      <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
    </p>

    <p>
      Collections may also listen for changes to specific attributes in their
      models, for example: <tt>Documents.bind("change:selected", ...)</tt>
    </p>

    <p id="Collection-extend">
      <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
      <br />
      To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
      providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
      directly to the collection's constructor function.
    </p>

    <p id="Collection-model">
      <b class="header">model</b><code>collection.model</code>
      <br />
      Override this property to specify the model class that the collection
      contains. If defined, you can pass raw attributes objects (and arrays) to
      <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
      and <a href="#Collection-refresh">refresh</a>, and the attributes will be
      converted into a model of the proper type.
    </p>

<pre>
var Library = Backbone.Collection.extend({
  model: Book
});
</pre>

    <p id="Collection-constructor">
      <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
      <br />
      When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
      The collection's <a href="#Collection-comparator">comparator</a> function
      may be included as an option. If you define an <b>initialize</b> function, it will be
      invoked when the collection is created.
    </p>

<pre>
var tabs = new TabSet([tab1, tab2, tab3]);
</pre>

    <p id="Collection-models">
      <b class="header">models</b><code>collection.models</code>
      <br />
      Raw access to the JavaScript array of models inside of the collection. Usually you'll
      want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
      to access model objects, but occasionally a direct reference to the array
      is desired.
    </p>

    <p id="Collection-toJSON">
      <b class="header">toJSON</b><code>collection.toJSON()</code>
      <br />
      Return an array containing the attributes hash of each model in the
      collection. This can be used to serialize and persist the
      collection as a whole. The name of this method is a bit confusing, because
      it conforms to
      <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
    </p>

<pre class="runnable">
var collection = new Backbone.Collection([
  {name: "Tim", age: 5},
  {name: "Ida", age: 26},
  {name: "Rob", age: 55}
]);

alert(JSON.stringify(collection));
</pre>

    <p id="Collection-Underscore-Methods">
      <b class="header">Underscore Methods (25)</b>
      <br />
      Backbone proxies to <b>Underscore.js</b> to provide 25 iteration functions
      on <b>Backbone.Collection</b>. They aren't all documented here, but
      you can take a look at the Underscore documentation for the full details&hellip;
    </p>

    <ul>
      <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
      <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
    </ul>

<pre>
Books.each(function(book) {
  book.publish();
});

var titles = Books.map(function(book) {
  return book.get("title");
});

var publishedBooks = Books.filter(function(book) {
  return book.get("published") === true;
});

var alphabetical = Books.sortBy(function(book) {
  return book.author.get("name").toLowerCase();
});
</pre>

    <p id="Collection-add">
      <b class="header">add</b><code>collection.add(models, [options])</code>
      <br />
      Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
      event, which you can pass <tt>{silent: true}</tt> to suppress. If a
      <a href="#Collection-model">model</a> property is defined, you may also pass
      raw attributes objects.
    </p>

<pre class="runnable">
var ships = new Backbone.Collection;

ships.bind("add", function(ship) {
  alert("Ahoy " + ship.get("name") + "!");
});

ships.add([
  {name: "Flying Dutchman"},
  {name: "Black Pearl"}
]);
</pre>

    <p id="Collection-remove">
      <b class="header">remove</b><code>collection.remove(models, [options])</code>
      <br />
      Remove a model (or an array of models) from the collection. Fires a
      <tt>"remove"</tt> event, which you can use <tt>silent</tt>
      to suppress.
    </p>

    <p id="Collection-get">
      <b class="header">get</b><code>collection.get(id)</code>
      <br />
      Get a model from a collection, specified by <b>id</b>.
    </p>

<pre>
var book = Library.get(110);
</pre>

    <p id="Collection-getByCid">
      <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
      <br />
      Get a model from a collection, specified by client id. The client id
      is the <tt>.cid</tt> property of the model, automatically assigned whenever
      a model is created. Useful for models which have not yet been saved to
      the server, and do not yet have true ids.
    </p>

    <p id="Collection-at">
      <b class="header">at</b><code>collection.at(index)</code>
      <br />
      Get a model from a collection, specified by index. Useful if your collection
      is sorted, and if your collection isn't sorted, <b>at</b> will still
      retrieve models in insertion order.
    </p>

    <p id="Collection-length">
      <b class="header">length</b><code>collection.length</code>
      <br />
      Like an array, a Collection maintains a <tt>length</tt> property, counting
      the number of models it contains.
    </p>

    <p id="Collection-comparator">
      <b class="header">comparator</b><code>collection.comparator</code>
      <br />
      By default there is no <b>comparator</b> function on a collection.
      If you define a comparator, it will be used to maintain
      the collection in sorted order. This means that as models are added,
      they are inserted at the correct index in <tt>collection.models</tt>.
      Comparator functions take a model and return a numeric or string value
      by which the model should be ordered relative to others.
    </p>

    <p>
      Note how even though all of the chapters in this example are added backwards,
      they come out in the proper order:
    </p>

<pre class="runnable">
var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("page");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));
</pre>

    <p class="warning">
      Brief aside: This comparator function is different than JavaScript's regular
      "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
      and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
    </p>

    <p id="Collection-sort">
      <b class="header">sort</b><code>collection.sort([options])</code>
      <br />
      Force a collection to re-sort itself. You don't need to call this under
      normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
      will maintain itself in proper sort order at all times. Calling <b>sort</b>
      triggers the collection's <tt>"refresh"</tt> event, unless silenced by passing
      <tt>{silent: true}</tt>
    </p>

    <p id="Collection-pluck">
      <b class="header">pluck</b><code>collection.pluck(attribute)</code>
      <br />
      Pluck an attribute from each model in the collection. Equivalent to calling
      <tt>map</tt>, and returning a single attribute from the iterator.
    </p>

<pre class="runnable">
var stooges = new Backbone.Collection([
  new Backbone.Model({name: "Curly"}),
  new Backbone.Model({name: "Larry"}),
  new Backbone.Model({name: "Moe"})
]);

var names = stooges.pluck("name");

alert(JSON.stringify(names));
</pre>

    <p id="Collection-url">
      <b class="header">url</b><code>collection.url or collection.url()</code>
      <br />
      Set the <b>url</b> property (or function) on a collection to reference
      its location on the server. Models within the collection will use <b>url</b>
      to construct URLs of their own.
    </p>

<pre>
var Notes = Backbone.Collection.extend({
  url: '/notes'
});

// Or, something more sophisticated:

var Notes = Backbone.Collection.extend({
  url: function() {
    return this.document.url() + '/notes';
  }
});
</pre>

    <p id="Collection-parse">
      <b class="header">parse</b><code>collection.parse(response)</code>
      <br />
      <b>parse</b> is called by Backbone whenever a collection's models are
      returned by the server, in <a href="#Collection-fetch">fetch</a>.
      The function is passed the raw <tt>response</tt> object, and should return
      the array of model attributes to be <a href="#Collection-add">added</a>
      to the collection. The default implementation is a no-op, simply passing
      through the JSON response. Override this if you need to work with a
      preexisting API, or better namespace your responses.
    </p>

<pre>
var Tweets = Backbone.Collection.extend({
  // The Twitter Search API returns tweets under "results".
  parse: function(response) {
    return response.results;
  }
});
</pre>

    <p id="Collection-fetch">
      <b class="header">fetch</b><code>collection.fetch([options])</code>
      <br />
      Fetch the default set of models for this collection from the server,
      refreshing the collection when they arrive. The <b>options</b> hash takes
      <tt>success</tt> and <tt>error</tt>
      callbacks which will be passed <tt>(collection, response)</tt> as arguments.
      When the model data returns from the server, the collection will
      <a href="#Collection-refresh">refresh</a>.
      Delegates to <a href="#Sync">Backbone.sync</a>
      under the covers, for custom persistence strategies.
      The server handler for <b>fetch</b> requests should return a JSON array of
      models.
    </p>

<pre class="runnable">
Backbone.sync = function(method, model) {
  alert(method + ": " + model.url);
};

var Accounts = new Backbone.Collection;
Accounts.url = '/accounts';

Accounts.fetch();
</pre>

    <p>
      Note that <b>fetch</b> should not be used to populate collections on
      page load &mdash; all models needed at load time should already be
      bootstrapped in to place. <b>fetch</b> is intended for lazily-loading models
      for interfaces that are not needed immediately: for example, documents
      with collections of notes that may be toggled open and closed.
    </p>

    <p id="Collection-refresh">
      <b class="header">refresh</b><code>collection.refresh(models, [options])</code>
      <br />
      Adding and removing models one at a time is all well and good, but sometimes
      you have so many models to change that you'd rather just update the collection
      in bulk. Use <b>refresh</b> to replace a collection with a new list
      of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
      at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
    </p>

    <p>
      Here's an example using <b>refresh</b> to bootstrap a collection during initial page load,
      in a Rails application.
    </p>

<pre>
&lt;script&gt;
  Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
&lt;/script&gt;
</pre>

    <p id="Collection-create">
      <b class="header">create</b><code>collection.create(attributes, [options])</code>
      <br />
      Convenience to create a new instance of a model within a collection.
      Equivalent to instantiating a model with a hash of attributes,
      saving the model to the server, and adding the model to the set after being
      successfully created. Returns
      the model, or <tt>false</tt> if a validation error prevented the
      model from being created. In order for this to work, your should set the
      <a href="#Collection-model">model</a> property of the collection.
    </p>

<pre>
var Library = Backbone.Collection.extend({
  model: Book
});

var NYPL = new Library;

var othello = NYPL.create({
  title: "Othello",
  author: "William Shakespeare"
});
</pre>

    <h2 id="Controller">Backbone.Controller</h2>

    <p>
      Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
      in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
      <b>Backbone.Controller</b> provides methods for routing client-side URL
      fragments, and connecting them to actions and events.
    </p>

    <p class="warning">
      Backbone controllers do not yet make use of HTML5 <b>pushState</b> and
      <b>replaceState</b>. Currently, <b>pushState</b> and <b>replaceState</b>
      need special handling on the server-side, cause you to mint duplicate URLs,
      and have an incomplete API. We may start supporting them in the future
      when these issues have been resolved.
    </p>

    <p>
      During page load, after your application has finished creating all of its controllers,
      be sure to call <tt>Backbone.history.start()</tt> to route the initial URL.
    </p>

    <p id="Controller-extend">
      <b class="header">extend</b><code>Backbone.Controller.extend(properties, [classProperties])</code>
      <br />
      Get started by creating a custom controller class. You'll
      want to define actions that are triggered when certain URL fragments are
      matched, and provide a <a href="#Controller-routes">routes</a> hash
      that pairs routes to actions.
    </p>

<pre>
var Workspace = Backbone.Controller.extend({

  routes: {
    "help":                 "help",    // #help
    "search/:query":        "search",  // #search/kiwis
    "search/:query/p:page": "search"   // #search/kiwis/p7
  },

  help: function() {
    ...
  },

  search: function(query, page) {
    ...
  }

});
</pre>

    <p id="Controller-routes">
      <b class="header">routes</b><code>controller.routes</code>
      <br />
      The routes hash maps URLs with parameters to functions on your controller,
      similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
      Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
      component between slashes; and splat parts <tt>*splat</tt>, which can match
      any number of URL components.
    </p>

    <p>
      For example, a route of <tt>"search/:query/p:page"</tt> will match
      a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
      and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
      match <tt>#file/nested/folder/file.txt</tt>,
      passing <tt>"nested/folder/file.txt"</tt> to the action.
    </p>

    <p>
      When the visitor presses the back button, or enters a URL, and a particular
      route is matched, the name of the action will be fired as an
      <a href="#Events">event</a>, so that other objects can listen to the controller,
      and be notified. In the following example, visiting <tt>#help/uploading</tt>
      will fire a <tt>route:help</tt> event from the controller.
    </p>

<pre>
routes: {
  "help/:page":         "help",
  "download/*path":     "download",
  "folder/:name":       "openFolder",
  "folder/:name-:mode": "openFolder"
}
</pre>

<pre>
controller.bind("route:help", function(page) {
  ...
});
</pre>

    <p id="Controller-constructor">
      <b class="header">constructor / initialize</b><code>new Controller([options])</code>
      <br />
      When creating a new controller, you may pass its
      <a href="#Controller-routes">routes</a> hash directly as an option, if you
      choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
      function, if defined.
    </p>

    <p id="Controller-route">
      <b class="header">route</b><code>controller.route(route, name, callback)</code>
      <br />
      Manually create a route for the controller, The <tt>route</tt> argument may
      be a <a href="#Controller-routes">routing string</a> or regular expression.
      Each matching capture from the route or regular expression will be passed as
      an argument to the callback. The <tt>name</tt> argument will be triggered as
      a <tt>"route:name"</tt> event whenever the route is matched.
    </p>

<pre>
initialize: function(options) {

  // Matches #page/10, passing "10"
  this.route("page/:number", "page", function(number){ ... });

  // Matches /117-a/b/c/open, passing "117-a/b/c"
  this.route(/^(.*?)\/open$/, "open", function(id){ ... });

}
</pre>

    <p id="Controller-saveLocation">
      <b class="header">saveLocation</b><code>controller.saveLocation(fragment)</code>
      <br />
      Whenever you reach a point in your application that you'd like to save
      as a URL, call <b>saveLocation</b> in order to update the URL fragment
      without triggering a <tt>hashchange</tt> event. (If you would prefer to
      trigger the event and routing, you can just set the hash directly.)
    </p>

<pre>
openPage: function(pageNumber) {
  this.document.pages.at(pageNumber).open();
  this.saveLocation("page/" + pageNumber);
}
</pre>

    <h2 id="History">Backbone.history</h2>

    <p>
      <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
      events, match the appropriate route, and trigger callbacks. You shouldn't
      ever have to create one of these yourself &mdash; you should use the reference
      to <tt>Backbone.history</tt> that will be created for you automatically if you make use
      of <a href="#Controller">Controllers</a> with <a href="#Controller-routes">routes</a>.
    </p>

    <p id="History-start">
      <b class="header">start</b><code>Backbone.history.start()</code>
      <br />
      When all of your <a href="#Controller">Controllers</a> have been created,
      and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
      to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
    </p>

<pre>
$(function(){
  new WorkspaceController();
  new HelpPaneController();
  Backbone.history.start();
});
</pre>

    <h2 id="Sync">Backbone.sync</h2>

    <p>
      <b>Backbone.sync</b> is the function the Backbone calls every time it
      attempts to read or save a model to the server. By default, it uses
      <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request. You can override
      it in order to use a different persistence strategy, such as WebSockets,
      XML transport, or Local Storage.
    </p>

    <p>
      The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, success, error)</tt>
    </p>

    <ul>
      <li><b>method</b> – the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
      <li><b>model</b> – the model to be saved (or collection to be read)</li>
      <li><b>success({model: ...})</b> – a callback that should be fired if the request works</li>
      <li><b>error({model: ...})</b> – a callback that should be fired if the request fails</li>
    </ul>

    <p>
      With the default implementation, when <b>Backbone.sync</b> sends up a request to save
      a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
      with content-type <tt>application/json</tt>. When returning a JSON response,
      send down the attributes of the  model that have been changed by the server, and need
      to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
      (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
      of model attribute objects.
    </p>

    <p>
      The default <b>sync</b> handler maps CRUD to REST like so:
    </p>

    <ul>
      <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
      <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
      <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
      <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
    </ul>

    <p>
      As an example, a Rails handler responding to an <tt>"update"</tt> call from
      <tt>Backbone</tt> might look like this: <i>(In real code, never use
      </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
      you allow to be changed.)</i>
    </p>

<pre>
def update
  account = Account.find params[:id]
  account.update_attributes params
  render :json => account
end
</pre>

    <p>
      One more tip for Rails integration is to disable the default namespacing for
      <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
    </p>

    <p id="Sync-emulateHTTP">
      <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
      <br />
      If you want to work with a legacy web server that doesn't support Backbones's
      default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
      Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
      a HTTP <tt>POST</tt>, and pass them under the <tt>_method</tt> parameter. Setting this option
      will also set an <tt>X-HTTP-Method-Override</tt> header with the true method.
    </p>

<pre>
Backbone.emulateHTTP = true;

model.save();  // POST to "/collection/id", with "_method=PUT" + header.
</pre>

    <p id="Sync-emulateJSON">
      <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
      <br />
      If you're working with a legacy web server that can't handle requests
      encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
      will cause the JSON to be serialized under a <tt>model</tt> parameter, and
      the request to be made with a <tt>application/x-www-form-urlencoded</tt>
      mime type, as if from an HTML form.
    </p>

    <h2 id="View">Backbone.View</h2>

    <p>
      Backbone views are almost more convention than they are code &mdash; they
      don't determine anything about your HTML or CSS for you, and can be used
      with any JavaScript templating library.
      The general idea is to organize your interface into logical views,
      backed by models, each of which can be updated independently when the
      model changes, without having to redraw the page. Instead of digging into
      a JSON object, looking up an element in the DOM, and updating the HTML by hand,
      you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
      event &mdash; and now everywhere that
      model data is displayed in the UI, it is always immediately up to date.
    </p>

    <p id="View-extend">
      <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
      <br />
      Get started with views by creating a custom view class. You'll want to
      override the <a href="#View-render">render</a> function, specify your
      declarative <a href="#View-delegateEvents">events</a>, and perhaps the
      <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
      element.
    </p>

<pre>
var DocumentRow = Backbone.View.extend({

  tagName: "li",

  className: "document-row",

  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    _.bindAll(this, "render");
  },

  render: function() {
    ...
  }

});
</pre>

    <p id="View-constructor">
      <b class="header">constructor / initialize</b><code>new View([options])</code>
      <br />
      When creating a new View, the options you pass are attached to the view
      as <tt>this.options</tt>, for future reference. There are several special
      options that, if passed, will be attached directly to the view:
      <tt>model</tt>, <tt>collection</tt>,
      <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, and <tt>tagName</tt>.
      If the view defines an <b>initialize</b> function, it will be called when
      the view is first created. If you'd like to create a view that references
      an element <i>already</i> in the DOM, pass in the element as an option:
      <tt>new View({el: existingElement})</tt>
    </p>

<pre>
var doc = Documents.first();

new DocumentRow({
  model: doc,
  id: "document-row-" + doc.id
});
</pre>

    <p id="View-el">
      <b class="header">el</b><code>view.el</code>
      <br />
      All views have a DOM element at all times (the <b>el</b> property),
      whether they've already been inserted into the page or not. In this
      fashion, views can be rendered at any time, and inserted into the DOM all
      at once, in order to get high-performance UI rendering with as few
      reflows and repaints as possible.
    </p>

    <p>
      <tt>this.el</tt> is created from the view's <tt>tagName</tt>, <tt>className</tt>,
      and <tt>id</tt> properties, if specified. If not, <b>el</b> is an empty <tt>div</tt>.
    </p>

    <p id="View-dollar">
      <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
      <br />
      If jQuery or Zepto is included on the page, each view has a
      <b>$</b> function that runs queries scoped within the view's element. If you use this
      scoped jQuery function, you don't have to use model ids as part of your query
      to pull out specific elements in a list, and can rely much more on HTML class
      attributes. It's equivalent to running: <tt>$(selector, this.el)</tt>
    </p>

<pre>
ui.Chapter = Backbone.View.extend({
  serialize : function() {
    return {
      title: this.$(".title").text(),
      start: this.$(".start-page").text(),
      end:   this.$(".end-page").text()
    };
  }
});
</pre>

    <p id="View-render">
      <b class="header">render</b><code>view.render()</code>
      <br />
      The default implementation of <b>render</b> is a no-op. Override this
      function with your code that renders the view template from model data,
      and updates <tt>this.el</tt> with the new HTML. A good
      convention is to <tt>return this</tt> at the end of <b>render</b> to
      enable chained calls.
    </p>

<pre>
var Bookmark = Backbone.View.extend({
  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }
});
</pre>

    <p>
      Backbone is agnostic with respect to your preferred method of HTML templating.
      Your <b>render</b> function could even munge together an HTML string, or use
      <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
      choosing a nice JavaScript templating library.
      <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
      <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
      <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
      Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
      <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
      is available, and is an excellent choice if you've already XSS-sanitized
      your interpolated data.
    </p>

    <p>
      Whatever templating strategy you end up with, it's nice if you <i>never</i>
      have to put strings of HTML in your JavaScript. At DocumentCloud, we
      use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
      to package up JavaScript templates stored in <tt>/app/views</tt> as part
      of our main <tt>core.js</tt> asset package.
    </p>

    <p id="View-remove">
      <b class="header">remove</b><code>view.remove()</code>
      <br />
      Convenience function for removing the view from the DOM. Equivalent to calling
      <tt>$(view.el).remove();</tt>
    </p>

    <p id="View-make">
      <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
      <br />
      Convenience function for creating a DOM element of the given type (<b>tagName</b>),
      with optional attributes and HTML content. Used internally to create the
      initial <tt>view.el</tt>.
    </p>

<pre class="runnable">
var view = new Backbone.View;

var el = view.make("b", {className: "bold"}, "Bold! ");

$("#make-demo").append(el);
</pre>

<div id="make-demo"></div>

    <p id="View-delegateEvents">
      <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
      <br />
      Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
      for DOM events within a view.
      If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
      as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
      Omitting the <tt>selector</tt> causes the event to be bound to the view's
      root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
      within the View's constructor for you, so if you have a simple <tt>events</tt>
      hash, all of your DOM events will always already be connected, and you will
      never have to call this function yourself.
    </p>

    <p>
      Using <b>delegateEvents</b> provides a number of advantages over manually
      using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
      callbacks are bound to the view before being handed off to jQuery, so when
      the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
      <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
      hash, all callbacks are removed and delegated afresh &mdash; useful for
      views which need to behave differently when in different modes.
    </p>

    <p>
      A view that displays a document in a search result might look
      something like this:
    </p>

<pre>
var DocumentView = Backbone.View.extend({

  events: {
    "dblclick"                : "open",
    "click .icon.doc"         : "select",
    "contextmenu .icon.doc"   : "showMenu",
    "click .show_notes"       : "toggleNotes",
    "click .title .lock"      : "editAccessLevel",
    "mouseover .title .date"  : "showTooltip"
  },

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  },

  open: function() {
    window.open(this.model.get("viewer_url"));
  },

  select: function() {
    this.model.set({selected: true});
  },

  ...

});
</pre>

    <h2 id="examples">Examples</h2>

    <p>
      <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
      <a href="examples/todos/index.html">Todo List application</a>
      that is bundled in the repository as Backbone example. If you're wondering
      where to get started with Backbone in general, take a moment to
      <a href="docs/todos.html">read through the annotated source</a>. The app uses a
      <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
      to transparently save all of your todos within your browser, instead of
      sending them to a server. Jérôme also has a version hosted at
      <a href="http://localtodos.com/">localtodos.com</a> that uses a
      <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
      instead of jQuery.
    </p>

    <div style="text-align: center;">
      <a href="examples/todos/index.html">
        <img src="docs/images/todos.png" alt="Todos" style="margin: 10px auto;" />
      </a>
    </div>

    <p>
      The <a href="http://www.documentcloud.org/">DocumentCloud</a> workspace
      is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
      <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
    </p>

    <div style="text-align: center;">
      <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" style="margin: 10px auto;" />
    </div>

    <p>
      <a href="http://bennolan.com/">Ben Nolan</a> created
      <a href="http://bennolan.com/2010/11/24/backbone-jquery-demo.html">an example "Backbone Mobile" application</a>, combining Backbone.js
      with <a href="http://jquerymobile.com/">jQuery Mobile</a>. You can
      <a href="http://bennolan.com/science/backbone-mobile/">try the app</a>
      in your browser, or view the
      <a href="https://github.com/bnolan/backbone-mobile">source code</a> on Github.
    </p>

    <div style="text-align: center;">
      <a href="http://bennolan.com/science/backbone-mobile/">
        <img src="docs/images/backbone-mobile.png" alt="Backbone Mobile" style="margin: 10px auto;" />
      </a>
    </div>

    <h2 id="changelog">Change Log</h2>

    <p>
      <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
      Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
      jQuery, as a framework for DOM manipulation and Ajax support.
      Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
      attributes intended for HTML interpolation. When trying to persist a model,
      failed requests will now trigger an <tt>"error"</tt> event. The 
      ubiquitous <tt>options</tt> argument is now passed as the final argument
      to all <tt>"change"</tt> events.
    </p>

    <p>
      <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
      Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
      overridden on a per-model, or per-collection basis. Fixed recursion error
      when calling <tt>save</tt> with no changed attributes, within a
      <tt>"change"</tt> event.
    </p>

    <p>
      <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
      All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
      model, so that views can listen for them without having to know about the
      collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
      <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
      Backbone routes are now able to load empty URL fragments.
    </p>

    <p>
      <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
      Backbone now has <a href="#Controller">Controllers</a> and
      <a href="#History">History</a>, for doing client-side routing based on
      URL fragments.
      Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
      do <tt>PUT</tt> and <tt>DELETE</tt>.
      Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
      encoded requests.
      Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
      from a model.
      All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
    </p>

    <p>
      <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
      Instead of requiring server responses to be namespaced under a <tt>model</tt>
      key, now you can define your own <a href="#Model-parse">parse</a> method
      to convert responses into attributes for Models and Collections.
      The old <tt>handleEvents</tt> function is now named
      <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
      called as part of the View's constructor.
      Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
      Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
    </p>

    <p>
      <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
      Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
      attributes of single model from the server.
      An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
      as an option, which will be invoked if validation fails, overriding the
      <tt>"error"</tt> event.
      You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
      methods by setting <tt>Backbone.emulateHTTP = true</tt>.
      Existing Model and Collection data is no longer sent up unnecessarily with
      <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
      Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
    </p>

    <p>
      <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
      Added a convention for <tt>initialize</tt> functions to be called
      upon instance construction, if defined. Documentation tweaks.
    </p>

    <p>
      <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
      Initial Backbone release.
    </p>

    <p>
      <br />
      <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
        <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
      </a>
    </p>

  </div>

  <script src="test/vendor/underscore-1.1.3.js"></script>
  <script src="test/vendor/jquery-1.4.2.js"></script>
  <script src="test/vendor/json2.js"></script>
  <script src="backbone.js"></script>

  <script>
    // Set up the "play" buttons for each runnable code example.
    $(function() {
      $('.runnable').each(function() {
        var code = this;
        var button = $('<div class="run" title="Run"></div>');
        $(button).insertBefore(code).bind('click', function(){
          eval($(code).text());
        });
      });
    });
  </script>

</body>
</html>