0% found this document useful (0 votes)
12 views50 pages

Backbone

Backbone.js is a JavaScript library that provides structure to web applications by offering models, collections, and views, facilitating the separation of business logic from the user interface. It allows for easy integration with RESTful APIs and includes features such as event handling and routing. The library is open-source and available under the MIT license, with resources for getting started, including documentation, examples, and a GitHub repository.

Uploaded by

kexegi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views50 pages

Backbone

Backbone.js is a JavaScript library that provides structure to web applications by offering models, collections, and views, facilitating the separation of business logic from the user interface. It allows for easy integration with RESTful APIs and includes features such as event handling and routing. The library is open-source and available under the MIT license, with resources for getting started, including documentation, examples, and a GitHub repository.

Uploaded by

kexegi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] (1.3.

3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
[Link] gives structure to web applications by providing models with key-value
– Collections
– API Integration binding and custom events, collections with a rich API of enumerable functions, views
– Rendering with declarative event handling, and connects it all to your existing API over a RESTful
– Routing
JSON interface.
Events
– on The project is hosted on GitHub, and the annotated source code is available, as well as
– off an online test suite, an example application, a list of tutorials and a long list of real-
– trigger
world projects that use Backbone. Backbone is available for use under the MIT
– once
– listenTo software license.
– stopListening
– listenToOnce
You can report bugs and discuss features on the GitHub issues page, on Freenode IRC
‑ Catalog of Built‑in Events
in the #documentcloud channel, post questions to the Google Group, add pages to the
Model wiki or send tweets to @documentcloud.
– extend
– constructor / initialize
Backbone is an open-source component of DocumentCloud.
– get
– set
– escape
– has
– unset
Downloads & Dependencies (Right‑click, and use "Save As")

– clear
– id
Development Version (1.3.3)
– idAttribute 72kb, Full source, tons of comments
– cid
– attributes
– changed Production Version (1.3.3) 7.6kb, Packed and gzipped
– defaults (Source Map)
– toJSON
– sync Edge Version (master) Unreleased, use at your own risk
– fetch
– save
– destroy
– Underscore Methods (9)
Backbone's only hard dependency is [Link] ( >= 1.8.3). For RESTful persistence
– validate
– validationError and DOM manipulation with [Link], include jQuery ( >= 1.11.0), and [Link]
– isValid for older Internet Explorer support. (Mimics of the Underscore and jQuery APIs, such as
– url
Lodash and Zepto, will also tend to work, with varying degrees of compatibility.)
– urlRoot
– parse
– clone
– isNew
– hasChanged
Getting Started
– changedAttributes
– previous When working on a web application that involves a lot of JavaScript, one of the first
– previousAttributes
things you learn is to stop tying your data to the DOM. It's all too easy to create
Collection JavaScript applications that end up as tangled piles of jQuery selectors and callbacks,
– extend all trying frantically to keep data in sync between the HTML UI, your JavaScript logic,
– model and the database on your server. For rich client-side applications, a more structured
– modelId
approach is often helpful.
– constructor / initialize
– models
– toJSON With Backbone, you represent your data as Models, which can be created, validated,
– sync
destroyed, and saved to the server. Whenever a UI action causes an attribute of a
– Underscore Methods (46)
– add model to change, the model triggers a "change" event; all the Views that display the
– remove model's state can be notified of the change, so that they are able to respond
– reset accordingly, re-rendering themselves with the new information. In a finished Backbone
– set
app, you don't have to write the glue code that looks into the DOM to find an element
– get
– at with a specific id, and update the HTML manually — when the model changes, the
– push views simply update themselves.
– pop
– unshift
– shift Philosophically, Backbone is an attempt to discover the minimal set of data-structuring
– slice (models and collections) and user interface (views and URLs) primitives that are
– length
generally useful when building web applications with JavaScript. In an ecosystem
– comparator
– sort where overarching, decides-everything-for-you frameworks are commonplace, and
– pluck many libraries require your site to be reorganized to suit their look, feel, and default
– where
behavior — Backbone should continue to be a tool that gives you the freedom to
– findWhere
– url design the full experience of your web application.
– parse
– clone
If you're new here, and aren't yet quite sure what Backbone is for, start by browsing the
– fetch
– create list of Backbone-based projects.

Router
Many of the code examples in this documentation are runnable, because Backbone is
– extend
included on this page. Click the play button to execute them.
– routes
– constructor / initialize
– route
– navigate
– execute
Models and Views
History
– start

Sync
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
The single most important thing that Backbone can help you with is keeping your
– Models and Views
– Collections business logic separate from your user interface. When the two are entangled, change
– API Integration is hard; when logic doesn't depend on UI, your interface becomes easier to work with.
– Rendering
– Routing
Model View
Events
Orchestrates data and business logic. Listens for changes and renders UI.
– on
– off Loads and saves from the server. Handles user input and interactivity.
– trigger
Emits events when data changes. Sends captured input to the model.
– once
– listenTo
– stopListening
– listenToOnce A Model manages an internal table of data attributes, and triggers "change" events
‑ Catalog of Built‑in Events when any of its data is modified. Models handle syncing data with a persistence layer
— usually a REST API with a backing database. Design your models as the atomic
Model
reusable objects containing all of the helpful functions for manipulating their particular
– extend
– constructor / initialize bit of data. Models should be able to be passed around throughout your app, and used
– get anywhere that bit of data is needed.
– set
– escape
– has A View is an atomic chunk of user interface. It often renders the data from a specific
– unset model, or number of models — but views can also be data-less chunks of UI that stand
– clear
alone. Models should be generally unaware of views. Instead, views listen to the model
– id
"change" events, and react or re-render themselves appropriately.
– idAttribute
– cid
– attributes
– changed
– defaults Collections
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
A Collection helps you deal with a group of related models, handling the loading and
– previous
– previousAttributes
saving of new models to the server and providing helper functions for performing
aggregations or computations against a list of models. Aside from their own events,
Collection collections also proxy through all of the events that occur to models within them,
– extend allowing you to listen in one place for any change that might happen to any model in
– model
the collection.
– modelId
– constructor / initialize
– models
– toJSON
– sync
API Integration
– Underscore Methods (46)
– add Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection
– remove
with the url of your resource endpoint:
– reset
– set
– get var Books = [Link]({
– at url: '/books'
– push
});
– pop
– unshift
– shift The Collection and Model components together form a direct mapping of REST
– slice
resources using the following methods:
– length
– comparator
– sort GET /books/ .... [Link]();
– pluck POST /books/ .... [Link]();
– where GET /books/1 ... [Link]();
– findWhere
PUT /books/1 ... [Link]();
– url
DEL /books/1 ... [Link]();
– parse
– clone
– fetch When fetching raw JSON data from an API, a Collection will automatically populate
– create
itself with data formatted as an array, while a Model will automatically populate itself
Router with data formatted as an object:
– extend
– routes [{"id": 1}] ..... populates a Collection with one model.
– constructor / initialize {"id": 1} ....... populates a Model with one attribute.
– route
– navigate
– execute However, it's fairly common to encounter APIs that return data in a different format than
what Backbone expects. For example, consider fetching a Collection from an API that
History
returns the real data array wrapped in metadata:
– start

Sync
{
"page": 1,
[Link] (1.3.3) "limit": 10,
» GitHub Repository "total": 2,
» Annotated Source "books": [
{"id": 1, "title": "Pride and Prejudice"},
Getting Started {"id": 4, "title": "The Great Gatsby"}
‑ Introduction ]
– Models and Views }
– Collections
– API Integration
– Rendering In the above example data, a Collection should populate using the "books" array
– Routing rather than the root object structure. This difference is easily reconciled using a parse
method that returns (or transforms) the desired portion of API data:
Events
– on
– off var Books = [Link]({
– trigger url: '/books',
– once parse: function(data) {
– listenTo return [Link];
– stopListening }
– listenToOnce });
‑ Catalog of Built‑in Events

Model
– extend View Rendering
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid
– attributes
– changed
– defaults
– toJSON Each View manages the rendering and user interaction within its own DOM element. If
– sync
you're strict about not allowing views to reach outside of themselves, it helps keep your
– fetch
– save interface flexible — allowing views to be rendered in isolation in any place where they
– destroy might be needed.
– Underscore Methods (9)
– validate
– validationError Backbone remains unopinionated about the process used to render View objects and
– isValid their subviews into UI: you define how your models get translated into HTML (or SVG,
– url
or Canvas, or something even more exotic). It could be as prosaic as a simple
– urlRoot
– parse Underscore template, or as fancy as the React virtual DOM. Some basic approaches to
– clone rendering views can be found in the Backbone primer.
– isNew
– hasChanged
– changedAttributes
– previous Routing with URLs
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
In rich web applications, we still want to provide linkable, bookmarkable, and shareable
– remove
– reset URLs to meaningful locations within an app. Use the Router to update the browser
– set URL whenever the user reaches a new "place" in your app that they might want to
– get
bookmark or share. Conversely, the Router detects changes to the URL — say,
– at
– push
pressing the "Back" button — and can tell your application exactly where you are now.
– pop
– unshift
– shift
– slice [Link]
– length
– comparator
Events is a module that can be mixed in to any object, giving the object the ability to
– sort
– pluck
bind and trigger custom named events. Events do not have to be declared before they
– where are bound, and may take passed arguments. For example:
– findWhere
– url
var object = {};
– parse
– clone
– fetch _.extend(object, [Link]);
– create
[Link]("alert", function(msg) {
Router alert("Triggered " + msg);
– extend });
– routes
– constructor / initialize [Link]("alert", "an event");
– route
– navigate
– execute
For example, to make a handy event dispatcher that can coordinate events among
different areas of your application: var dispatcher = _.clone([Link])
History
– start
on [Link](event, callback, [context]) Alias: bind
Sync
Bind a callback function to an object. The callback will be invoked whenever the event
is fired. If you have a large number of different events on a page, the convention is to
[Link] (1.3.3)
use colons to namespace them: "poll:start", or "change:selection". The event
» GitHub Repository
» Annotated Source string may also be a space-delimited list of several events...

Getting Started
[Link]("change:title change:author", ...);
‑ Introduction
– Models and Views
– Collections Callbacks bound to the special "all" event will be triggered when any event occurs,
– API Integration and are passed the name of the event as the first argument. For example, to proxy all
– Rendering
events from one object to another:
– Routing

Events [Link]("all", function(eventName) {


– on [Link](eventName);
– off });
– trigger
– once
– listenTo All Backbone event methods also support an event map syntax, as an alternative to
– stopListening positional arguments:
– listenToOnce
‑ Catalog of Built‑in Events
[Link]({
Model "change:author": [Link],
– extend "change:title change:subtitle": [Link],
– constructor / initialize "destroy": [Link]
– get });
– set
– escape
– has To supply a context value for this when the callback is invoked, pass the optional last
– unset argument: [Link]('change', [Link], this) or [Link]({change:
– clear [Link]}, this).
– id
– idAttribute
– cid
– attributes
off [Link]([event], [callback], [context]) Alias: unbind
– changed Remove a previously-bound callback function from an object. If no context is
– defaults
specified, all of the versions of the callback with different contexts will be removed. If no
– toJSON
– sync callback is specified, all callbacks for the event will be removed. If no event is specified,
– fetch callbacks for all events will be removed.
– save
– destroy
– Underscore Methods (9) // Removes just the `onChange` callback.
– validate [Link]("change", onChange);
– validationError
– isValid // Removes all "change" callbacks.
– url [Link]("change");
– urlRoot
– parse // Removes the `onChange` callback for all events.
– clone [Link](null, onChange);
– isNew
– hasChanged // Removes all callbacks for `context` for all events.
– changedAttributes [Link](null, null, context);
– previous
– previousAttributes
// Removes all callbacks on `object`.
[Link]();
Collection
– extend
– model Note that calling [Link](), for example, will indeed remove all events on the model
– modelId — including events that Backbone uses for internal bookkeeping.
– constructor / initialize
– models
– toJSON
– sync
trigger [Link](event, [*args])

– Underscore Methods (46) Trigger callbacks for the given event, or space-delimited list of events. Subsequent
– add
arguments to trigger will be passed along to the event callbacks.
– remove
– reset
– set
– get
once [Link](event, callback, [context])
– at Just like on, but causes the bound callback to fire only once before being removed.
– push
Handy for saying "the next time that X happens, do this". When multiple events are
– pop
– unshift passed in using the space separated syntax, the event will fire once for every event you
– shift passed in, not once for a combination of all events
– slice
– length
– comparator
listenTo [Link](other, event, callback)
– sort
– pluck Tell an object to listen to a particular event on an other object. The advantage of using
– where this form, instead of [Link](event, callback, object), is that listenTo allows the
– findWhere
object to keep track of the events, and they can be removed all at once later on. The
– url
– parse callback will always be called with object as context.
– clone
– fetch
[Link](model, 'change', [Link]);
– create

Router
– extend
stopListening [Link]([other], [event], [callback])

– routes Tell an object to stop listening to events. Either call stopListening with no arguments
– constructor / initialize
to have the object remove all of its registered callbacks ... or be more precise by telling
– route
– navigate it to remove just the events it's listening to on a specific object, or a specific event, or
– execute just a specific callback.

History
[Link]();
– start

Sync
[Link](model);

[Link] (1.3.3)

» GitHub Repository listenToOnce [Link](other, event, callback)


» Annotated Source
Just like listenTo, but causes the bound callback to fire only once before being
Getting Started removed.
‑ Introduction
– Models and Views
– Collections Catalog of Events
– API Integration
Here's the complete list of built-in Backbone events, with arguments. You're also free to
– Rendering
– Routing trigger your own events on Models, Collections and Views as you see fit. The Backbone
object itself mixes in Events, and can be used to emit any global events that your
Events application needs.
– on
– off
"add" (model, collection, options) — when a model is added to a collection.
– trigger
– once "remove" (model, collection, options) — when a model is removed from a collection.
– listenTo
– stopListening "update" (collection, options) — single event triggered after any number of models have been added
– listenToOnce or removed from a collection.
‑ Catalog of Built‑in Events
"reset" (collection, options) — when the collection's entire contents have been reset.

Model "sort" (collection, options) — when the collection has been re-sorted.
– extend
"change" (model, options) — when a model's attributes have changed.
– constructor / initialize
– get "change:[attribute]" (model, value, options) — when a specific attribute has been updated.
– set
– escape "destroy" (model, collection, options) — when a model is destroyed.
– has
"request" (model_or_collection, xhr, options) — when a model or collection has started a request to
– unset
the server.
– clear
– id "sync" (model_or_collection, response, options) — when a model or collection has been successfully
– idAttribute synced with the server.
– cid
– attributes "error" (model_or_collection, response, options) — when a model's or collection's request to the
– changed server has failed.
– defaults
"invalid" (model, error, options) — when a model's validation fails on the client.
– toJSON
– sync "route:[name]" (params) — Fired by the router when a specific route is matched.
– fetch
– save "route" (route, params) — Fired by the router when any route has been matched.
– destroy
"route" (router, route, params) — Fired by history when any route has been matched.
– Underscore Methods (9)
– validate "all" — this special event fires for any triggered event, passing the event name as the first argument
– validationError followed by all trigger arguments.
– isValid
– url
– urlRoot Generally speaking, when calling a function that emits an event ( [Link],
– parse [Link], and so on...), if you'd like to prevent the event from being triggered,
– clone
you may pass {silent: true} as an option. Note that this is rarely, perhaps even
– isNew
– hasChanged never, a good idea. Passing through a specific flag in the options for your event callback
– changedAttributes to look at, and choose to ignore, will usually work out better.
– previous
– previousAttributes

Collection [Link]
– extend
– model
Models are the heart of any JavaScript application, containing the interactive data as
– modelId
– constructor / initialize well as a large part of the logic surrounding it: conversions, validations, computed
– models properties, and access control. You extend [Link] with your domain-specific
– toJSON
methods, and Model provides a basic set of functionality for managing changes.
– sync
– Underscore Methods (46)
– add The following is a contrived example, but it demonstrates defining a model with a
– remove
custom method, setting an attribute, and firing an event keyed to changes in that
– reset
– set specific attribute. After running this code once, sidebar will be available in your
– get browser's console, so you can play around with it.
– at
– push
– pop var Sidebar = [Link]({
– unshift promptColor: function() {
– shift var cssColor = prompt("Please enter a CSS color:");
– slice [Link]({color: cssColor});
– length }
– comparator });
– sort
– pluck [Link] = new Sidebar;
– where
– findWhere
[Link]('change:color', function(model, color) {
– url
$('#sidebar').css({background: color});
– parse
});
– clone
– fetch
[Link]({color: 'white'});
– create

Router [Link]();

– extend
– routes
– constructor / initialize extend [Link](properties, [classProperties])
– route To create a Model class of your own, you extend [Link] and provide
– navigate
instance properties, as well as optional classProperties to be attached directly to the
– execute
constructor function.
History
– start
extend correctly sets up the prototype chain, so subclasses created with extend can

Sync
be further extended and subclassed as far as you like.

[Link] (1.3.3)
var Note = [Link]({
» GitHub Repository
» Annotated Source
initialize: function() { ... },
Getting Started
author: function() { ... },
‑ Introduction
– Models and Views
coordinates: function() { ... },
– Collections
– API Integration
– Rendering allowedToEdit: function(account) {
– Routing return true;
}
Events
– on });
– off
– trigger var PrivateNote = [Link]({
– once
– listenTo allowedToEdit: function(account) {
– stopListening return [Link](this);
– listenToOnce }
‑ Catalog of Built‑in Events
});
Model
– extend
Brief aside on super: JavaScript does not provide a simple way to call super — the function of the
– constructor / initialize
same name defined higher on the prototype chain. If you override a core function like set, or save,
– get
and you want to invoke the parent object's implementation, you'll have to explicitly call it, along these
– set
– escape lines:
– has
– unset
var Note = [Link]({
– clear
set: function(attributes, options) {
– id
[Link](this, arguments);
– idAttribute
...
– cid
}
– attributes
});
– changed
– defaults
– toJSON
– sync constructor / initialize new Model([attributes], [options])
– fetch
When creating an instance of a model, you can pass in the initial values of the
– save
– destroy attributes, which will be set on the model. If you define an initialize function, it will be
– Underscore Methods (9) invoked when the model is created.
– validate
– validationError
– isValid new Book({
– url title: "One Thousand and One Nights",
– urlRoot author: "Scheherazade"
– parse });
– clone
– isNew
– hasChanged In rare cases, if you're looking to get fancy, you may want to override constructor,
– changedAttributes which allows you to replace the actual constructor function for your model.
– previous
– previousAttributes
var Library = [Link]({
Collection constructor: function() {
[Link] = new Books();
– extend
– model [Link](this, arguments);
– modelId },
– constructor / initialize parse: function(data, options) {
– models [Link]([Link]);
– toJSON return [Link];
– sync }
– Underscore Methods (46) });
– add
– remove
– reset If you pass a {collection: ...} as the options, the model gains a collection
– set property that will be used to indicate which collection the model belongs to, and is used
– get
to help compute the model's url. The [Link] property is normally created
– at
– push automatically when you first add a model to a collection. Note that the reverse is not
– pop true, as passing this option to the constructor will not automatically add the model to
– unshift
the collection. Useful, sometimes.
– shift
– slice
– length If {parse: true} is passed as an option, the attributes will first be converted by
– comparator
parse before being set on the model.
– sort
– pluck
– where
– findWhere
get [Link](attribute)
– url Get the current value of an attribute from the model. For example: [Link]("title")
– parse
– clone
– fetch
set [Link](attributes, [options])
– create
Set a hash of attributes (one or many) on the model. If any of the attributes change the
Router model's state, a "change" event will be triggered on the model. Change events for
– extend
specific attributes are also triggered, and you can bind to those as well, for example:
– routes
change:title, and change:content. You may also pass individual keys and values.
– constructor / initialize
– route
– navigate
[Link]({title: "March 20", content: "In his eyes she eclipses..."});
– execute

[Link]("title", "A Scandal in Bohemia");


History
– start

Sync
escape [Link](attribute)
[Link] (1.3.3) Similar to get, but returns the HTML-escaped version of a model's attribute. If you're
» GitHub Repository interpolating data from the model into HTML, using escape to retrieve attributes will
» Annotated Source
prevent XSS attacks.
Getting Started
‑ Introduction var hacker = new [Link]({
– Models and Views name: "<script>alert('xss')</script>"
– Collections });
– API Integration
– Rendering alert([Link]('name'));
– Routing

Events
has [Link](attribute)
– on
– off Returns true if the attribute is set to a non-null or non-undefined value.
– trigger
– once
if ([Link]("title")) {
– listenTo
...
– stopListening
}
– listenToOnce
‑ Catalog of Built‑in Events

Model unset [Link](attribute, [options])

– extend Remove an attribute by deleting it from the internal attributes hash. Fires a "change"
– constructor / initialize
event unless silent is passed as an option.
– get
– set
– escape
– has clear [Link]([options])
– unset Removes all attributes from the model, including the id attribute. Fires a "change"
– clear
event unless silent is passed as an option.
– id
– idAttribute
– cid
– attributes id [Link]
– changed
A special property of models, the id is an arbitrary string (integer id or UUID). If you set
– defaults
– toJSON the id in the attributes hash, it will be copied onto the model as a direct property.
– sync Models can be retrieved by id from collections, and the id is used to generate model
– fetch URLs by default.
– save
– destroy
– Underscore Methods (9)
– validate
idAttribute [Link]

– validationError A model's unique identifier is stored under the id attribute. If you're directly
– isValid
communicating with a backend (CouchDB, MongoDB) that uses a different unique key,
– url
– urlRoot you may set a Model's idAttribute to transparently map from that key to id.
– parse
– clone
var Meal = [Link]({
– isNew
idAttribute: "_id"
– hasChanged
});
– changedAttributes
– previous
var cake = new Meal({ _id: 1, name: "Cake" });
– previousAttributes
alert("Cake id: " + [Link]);
Collection
– extend
– model cid [Link]
– modelId A special property of models, the cid or client id is a unique identifier automatically
– constructor / initialize
assigned to all models when they're first created. Client ids are handy when the model
– models
– toJSON has not yet been saved to the server, and does not yet have its eventual true id, but
– sync already needs to be visible in the UI.
– Underscore Methods (46)
– add
– remove
attributes [Link]
– reset
– set The attributes property is the internal hash containing the model's state — usually (but
– get not necessarily) a form of the JSON object representing the model data on the server.
– at
It's often a straightforward serialization of a row from the database, but it could also be
– push
– pop client-side computed state.
– unshift
– shift
– slice
Please use set to update the attributes instead of modifying them directly. If you'd like
– length to retrieve and munge a copy of the model's attributes, use
– comparator _.clone([Link]) instead.
– sort
– pluck
– where Due to the fact that Events accepts space separated lists of events, attribute names should not include
– findWhere spaces.
– url
– parse
– clone changed [Link]
– fetch
– create
The changed property is the internal hash containing all the attributes that have
changed since its last set. Please do not update changed directly since its state is
Router internally maintained by set. A copy of changed can be acquired from
– extend changedAttributes.
– routes
– constructor / initialize
– route
defaults [Link] or [Link]()
– navigate
– execute The defaults hash (or function) 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
History
their default value.
– start

Sync
var Meal = [Link]({
defaults: {
[Link] (1.3.3) "appetizer": "caesar salad",
» GitHub Repository "entree": "ravioli",
» Annotated Source "dessert": "cheesecake"
}
Getting Started });
‑ Introduction
– Models and Views alert("Dessert will be " + (new Meal).get('dessert'));
– Collections
– API Integration
Remember that in JavaScript, objects are passed by reference, so if you include an object as a default
– Rendering
– Routing value, it will be shared among all instances. Instead, define defaults as a function.

Events
– on
toJSON [Link]([options])

– off Return a shallow copy of the model's attributes for JSON stringification. This can be
– trigger
used for persistence, serialization, or for augmentation before being sent to the server.
– once
– listenTo The name of this method is a bit confusing, as it doesn't actually return a JSON string
– stopListening — but I'm afraid that it's the way that the JavaScript API for [Link] works.
– listenToOnce
‑ Catalog of Built‑in Events
var artist = new [Link]({
Model firstName: "Wassily",
lastName: "Kandinsky"
– extend
});
– constructor / initialize
– get
– set [Link]({birthday: "December 16, 1866"});
– escape
– has alert([Link](artist));
– unset
– clear
– id sync [Link](method, model, [options])
– idAttribute
– cid Uses [Link] to persist the state of a model to the server. Can be overridden for
– attributes custom behavior.
– changed
– defaults
– toJSON fetch [Link]([options])
– sync
– fetch Merges the model's state with attributes fetched from the server by delegating to
– save [Link]. Returns a jqXHR. Useful if the model has never been populated with
– destroy
data, or if you'd like to ensure that you have the latest server state. Triggers a
– Underscore Methods (9)
– validate "change" event if the server's state differs from the current attributes. fetch accepts
– validationError success and error callbacks in the options hash, which are both passed (model,
– isValid
response, options) as arguments.
– url
– urlRoot
– parse // Poll every 10 seconds to keep the channel model up-to-date.
– clone setInterval(function() {
– isNew [Link]();
– hasChanged }, 10000);
– changedAttributes
– previous
– previousAttributes
save [Link]([attributes], [options])

Collection Save a model to your database (or alternative persistence layer), by delegating to
– extend [Link]. Returns a jqXHR if validation is successful and false otherwise. The
– model
attributes hash (as in set) should contain the attributes you'd like to change — keys
– modelId
– constructor / initialize that aren't mentioned won't be altered — but, a complete representation of the resource
– models will be sent to the server. As with set, you may pass individual keys and values instead
– toJSON of a hash. If the model has a validate method, and validation fails, the model will not be
– sync
saved. If the model isNew, the save will be a "create" (HTTP POST), if the model
– Underscore Methods (46)
– add already exists on the server, the save will be an "update" (HTTP PUT).
– remove
– reset
– set
If instead, you'd only like the changed attributes to be sent to the server, call
– get [Link](attrs, {patch: true}). You'll get an HTTP PATCH request to the server
– at with just the passed-in attributes.
– push
– pop
– unshift Calling save with new attributes will cause a "change" event immediately, a
– shift "request" event as the Ajax request begins to go to the server, and a "sync" event
– slice
after the server has acknowledged the successful change. Pass {wait: true} if you'd
– length
– comparator like to wait for the server before setting the new attributes on the model.
– sort
– pluck
– where
In the following example, notice how our overridden version of [Link] receives
– findWhere a "create" request the first time the model is saved and an "update" request the
– url second time.
– parse
– clone
– fetch [Link] = function(method, model) {
– create alert(method + ": " + [Link](model));
[Link]('id', 1);
Router };
– extend
– routes var book = new [Link]({
– constructor / initialize title: "The Rough Riders",
– route author: "Theodore Roosevelt"
– navigate });
– execute
[Link]();
History
– start [Link]({author: "Teddy"});

Sync
save accepts success and error callbacks in the options hash, which will be passed
the arguments (model, response, options). If a server-side validation fails, return a
[Link] (1.3.3)
non- 200 HTTP response code, along with an error response in text or JSON.
» GitHub Repository
» Annotated Source
[Link]("author", "F.D.R.", {error: function(){ ... }});
Getting Started
‑ Introduction
– Models and Views destroy [Link]([options])
– Collections
– API Integration Destroys the model on the server by delegating an HTTP DELETE request to
– Rendering [Link]. Returns a jqXHR object, or false if the model isNew. Accepts
– Routing
success and error callbacks in the options hash, which will be passed (model,
response, options). Triggers a "destroy" event on the model, which will bubble up
Events
– on
through any collections that contain it, a "request" event as it begins the Ajax request
– off to the server, and a "sync" event, after the server has successfully acknowledged the
– trigger model's deletion. Pass {wait: true} if you'd like to wait for the server to respond
– once
before removing the model from the collection.
– listenTo
– stopListening
– listenToOnce [Link]({success: function(model, response) {
‑ Catalog of Built‑in Events ...
}});
Model
– extend
– constructor / initialize
Underscore Methods (9)
– get
– set Backbone proxies to [Link] to provide 9 object functions on [Link].
– escape They aren't all documented here, but you can take a look at the Underscore
– has
documentation for the full details…
– unset
– clear
– id keys
– idAttribute
– cid values
– attributes
pairs
– changed
– defaults invert
– toJSON
– sync pick
– fetch
omit
– save
– destroy chain
– Underscore Methods (9)
isEmpty
– validate
– validationError
– isValid [Link]('first_name', 'last_name', 'email');
– url
– urlRoot
[Link]().join(', ');
– parse
– clone
– isNew
– hasChanged validate [Link](attributes, options)
– changedAttributes This method is left undefined and you're encouraged to override it with any custom
– previous
validation logic you have that can be performed in JavaScript. By default save checks
– previousAttributes
validate before setting any attributes but you may also tell set to validate the new
Collection attributes by passing {validate: true} as an option.
– extend The validate method receives the model attributes as well as any options passed to
– model
set or save. If the attributes are valid, don't return anything from validate; if they are
– modelId
– constructor / initialize invalid return an error of your choosing. It can be as simple as a string error message to
– models be displayed, or a complete error object that describes the error programmatically. If
– toJSON
validate returns an error, save will not continue, and the model attributes will not be
– sync
– Underscore Methods (46)
modified on the server. Failed validations trigger an "invalid" event, and set the
– add validationError property on the model with the value returned by this method.
– remove
– reset
var Chapter = [Link]({
– set
– get validate: function(attrs, options) {
– at if ([Link] < [Link]) {
– push return "can't end before it starts";
– pop }
– unshift }
– shift });
– slice
– length var one = new Chapter({
– comparator title : "Chapter One: The Beginning"
– sort });
– pluck
– where
[Link]("invalid", function(model, error) {
– findWhere
alert([Link]("title") + " " + error);
– url
});
– parse
– clone
[Link]({
– fetch
start: 15,
– create
end: 10
Router });

– extend
– routes "invalid" events are useful for providing coarse-grained error messages at the model
– constructor / initialize
or collection level.
– route
– navigate
– execute
validationError [Link]
History The value returned by validate during the last failed validation.
– start

Sync
isValid [Link]()
[Link] (1.3.3) Run validate to check the model state.
» GitHub Repository
» Annotated Source
var Chapter = [Link]({
Getting Started validate: function(attrs, options) {
if ([Link] < [Link]) {
‑ Introduction
return "can't end before it starts";
– Models and Views
}
– Collections
}
– API Integration
– Rendering });
– Routing
var one = new Chapter({
Events title : "Chapter One: The Beginning"
});
– on
– off
– trigger [Link]({
– once start: 15,
– listenTo end: 10
– stopListening });
– listenToOnce
‑ Catalog of Built‑in Events if (![Link]()) {
alert([Link]("title") + " " + [Link]);
Model }
– extend
– constructor / initialize
– get url [Link]()
– set
– escape Returns the relative URL where the model's resource would be located on the server. If
– has your models are located somewhere else, override this method with the correct logic.
– unset
Generates URLs of the form: "[[Link]]/[id]" by default, but you may
– clear
– id
override by specifying an explicit urlRoot if the model's collection shouldn't be taken
– idAttribute into account.
– cid
– attributes
– changed Delegates to Collection#url to generate the URL, so make sure that you have it defined,
– defaults or a urlRoot property, if all models of this class share a common root URL. A model with
– toJSON an id of 101, stored in a [Link] with a url of "/documents/7/notes",
– sync
would have this URL: "/documents/7/notes/101"
– fetch
– save
– destroy
– Underscore Methods (9) urlRoot [Link] or [Link]()
– validate
Specify a urlRoot if you're using a model outside of a collection, to enable the default
– validationError
– isValid url function to generate URLs based on the model id. "[urlRoot]/id"
– url Normally, you won't need to define this. Note that urlRoot may also be a function.
– urlRoot
– parse
– clone var Book = [Link]({urlRoot : '/books'});
– isNew
– hasChanged var solaris = new Book({id: "1083-lem-solaris"});
– changedAttributes
– previous alert([Link]());
– previousAttributes

Collection parse [Link](response, options)


– extend
parse is called whenever a model's data is returned by the server, in fetch, and save.
– model
– modelId The function is passed the raw response object, and should return the attributes hash
– constructor / initialize to be set on the model. The default implementation is a no-op, simply passing through
– models
the JSON response. Override this if you need to work with a preexisting API, or better
– toJSON
– sync namespace your responses.
– Underscore Methods (46)
– add
If you're working with a Rails backend that has a version prior to 3.1, you'll notice that
– remove
– reset its default to_json implementation includes a model's attributes under a namespace.
– set To disable this behavior for seamless Backbone integration, set:
– get
– at
– push ActiveRecord::Base.include_root_in_json = false
– pop
– unshift
– shift clone [Link]()
– slice
– length
Returns a new instance of the model with identical attributes.
– comparator
– sort
– pluck isNew [Link]()
– where
Has this model been saved to the server yet? If the model does not yet have an id, it
– findWhere
– url is considered to be new.
– parse
– clone
– fetch hasChanged [Link]([attribute])
– create
Has the model changed since its last set? If an attribute is passed, returns true if that
Router specific attribute has changed.
– extend
– routes Note that this method, and the following change-related ones, are only useful during the course of a
– constructor / initialize "change" event.
– route
– navigate
– execute [Link]("change", function() {
if ([Link]("title")) {
History ...
– start }
});
Sync
changedAttributes [Link]([attributes])
[Link] (1.3.3) Retrieve a hash of only the model's attributes that have changed since the last set, or
» GitHub Repository false if there are none. Optionally, an external attributes hash can be passed in,
» Annotated Source
returning the attributes in that hash which differ from the model. This can be used to
Getting Started figure out which portions of a view should be updated, or what calls need to be made to
‑ Introduction sync the changes to the server.
– Models and Views
– Collections
– API Integration previous [Link](attribute)
– Rendering
– Routing
During a "change" event, this method can be used to get the previous value of a
changed attribute.
Events
– on
var bill = new [Link]({
– off
name: "Bill Smith"
– trigger
});
– once
– listenTo
[Link]("change:name", function(model, name) {
– stopListening
alert("Changed name from " + [Link]("name") + " to " + name);
– listenToOnce
‑ Catalog of Built‑in Events });

Model [Link]({name : "Bill Jones"});

– extend
– constructor / initialize
– get previousAttributes [Link]()
– set
Return a copy of the model's previous attributes. Useful for getting a diff between
– escape
– has versions of a model, or getting back to a valid state after an error occurs.
– unset
– clear
– id
– idAttribute [Link]
– cid
– attributes
Collections are ordered sets of models. You can bind "change" events to be notified
– changed
– defaults when any model in the collection has been modified, listen for "add" and "remove"
– toJSON events, fetch the collection from the server, and use a full suite of [Link]
– sync methods.
– fetch
– save
– destroy Any event that is triggered on a model in a collection will also be triggered on the
– Underscore Methods (9)
collection directly, for convenience. This allows you to listen for changes to specific
– validate
– validationError
attributes in any model in a collection, for example: [Link]("change:selected",
– isValid ...)
– url
– urlRoot
– parse extend [Link](properties, [classProperties])
– clone
– isNew To create a Collection class of your own, extend [Link], providing
– hasChanged instance properties, as well as optional classProperties to be attached directly to the
– changedAttributes
collection's constructor function.
– previous
– previousAttributes

Collection
model [Link]([attrs], [options])

– extend Override this property to specify the model class that the collection contains. If defined,
– model you can pass raw attributes objects (and arrays) to add, create, and reset, and the
– modelId
attributes will be converted into a model of the proper type.
– constructor / initialize
– models
– toJSON var Library = [Link]({
– sync model: Book
– Underscore Methods (46) });
– add
– remove
– reset A collection can also contain polymorphic models by overriding this property with a
– set
constructor that returns a model.
– get
– at
– push var Library = [Link]({
– pop
– unshift model: function(attrs, options) {
– shift if (condition) {
– slice
return new PublicDocument(attrs, options);
– length
} else {
– comparator
return new PrivateDocument(attrs, options);
– sort
}
– pluck
}
– where
– findWhere
– url });
– parse
– clone
– fetch modelId [Link](attrs)
– create
Override this method to return the value the collection will use to identify a model given
Router its attributes. Useful for combining models from multiple tables with different
– extend idAttribute values into a single collection.
– routes
– constructor / initialize
– route
By default returns the value of the attributes' idAttribute from the collection's model
– navigate class or failing that, id. If your collection uses a model factory and those models have
– execute an idAttribute other than id you must override this method.

History
var Library = [Link]({
– start
modelId: function(attrs) {
Sync
return [Link] + [Link];
}
[Link] (1.3.3) });
» GitHub Repository
» Annotated Source var library = new Library([
{type: 'dvd', id: 1},
Getting Started {type: 'vhs', id: 1}
‑ Introduction ]);
– Models and Views
– Collections var dvdId = [Link]('dvd1').id;
– API Integration var vhsId = [Link]('vhs1').id;
– Rendering alert('dvd: ' + dvdId + ', vhs: ' + vhsId);
– Routing

Events constructor / initialize new [Link]([models], [options])


– on
– off
When creating a Collection, you may choose to pass in the initial array of models. The
– trigger collection's comparator may be included as an option. Passing false as the
– once comparator option will prevent sorting. If you define an initialize function, it will be
– listenTo
invoked when the collection is created. There are a couple of options that, if provided,
– stopListening
– listenToOnce are attached to the collection directly: model and comparator.
‑ Catalog of Built‑in Events Pass null for models to create an empty Collection with options.

Model
var tabs = new TabSet([tab1, tab2, tab3]);
– extend
var spaces = new [Link](null, {
– constructor / initialize
model: Space
– get
– set });
– escape
– has
– unset models [Link]
– clear
Raw access to the JavaScript array of models inside of the collection. Usually you'll
– id
– idAttribute want to use get, at, or the Underscore methods to access model objects, but
– cid occasionally a direct reference to the array is desired.
– attributes
– changed
– defaults
toJSON [Link]([options])
– toJSON
– sync Return an array containing the attributes hash of each model (via toJSON) in the
– fetch collection. This can be used to serialize and persist the collection as a whole. The name
– save
of this method is a bit confusing, because it conforms to JavaScript's JSON API.
– destroy
– Underscore Methods (9)
– validate var collection = new [Link]([
– validationError
{name: "Tim", age: 5},
– isValid
{name: "Ida", age: 26},
– url
{name: "Rob", age: 55}
– urlRoot
]);
– parse
– clone
alert([Link](collection));
– isNew
– hasChanged
– changedAttributes
– previous sync [Link](method, collection, [options])
– previousAttributes
Uses [Link] to persist the state of a collection to the server. Can be overridden
Collection for custom behavior.
– extend
– model
– modelId Underscore Methods (46)
– constructor / initialize
Backbone proxies to [Link] to provide 46 iteration functions on
– models
– toJSON
[Link]. They aren't all documented here, but you can take a look at the
– sync Underscore documentation for the full details…
– Underscore Methods (46)
– add
– remove Most methods can take an object or string to support model-attribute-style predicates
– reset or a function that receives the model instance as an argument.
– set
– get
forEach (each)
– at
– push map (collect)
– pop
– unshift reduce (foldl, inject)
– shift
reduceRight (foldr)
– slice
– length find (detect)
– comparator
– sort findIndex
– pluck
findLastIndex
– where
– findWhere filter (select)
– url
– parse reject
– clone
every (all)
– fetch
– create some (any)

Router contains (includes)

– extend invoke
– routes
– constructor / initialize max
– route
min
– navigate
– execute sortBy

groupBy
History
– start shuffle

Sync
toArray

[Link] (1.3.3)
size

» GitHub Repository first (head, take)


» Annotated Source
initial
Getting Started rest (tail, drop)
‑ Introduction
last
– Models and Views
– Collections without
– API Integration
– Rendering indexOf
– Routing
lastIndexOf

Events isEmpty
– on
chain
– off
– trigger difference
– once
– listenTo sample
– stopListening
partition
– listenToOnce
‑ Catalog of Built‑in Events countBy

Model indexBy

– extend
– constructor / initialize [Link](function(book) {
– get [Link]();
– set });
– escape
– has
var titles = [Link]("title");
– unset
– clear
var publishedBooks = [Link]({published: true});
– id
– idAttribute
var alphabetical = [Link](function(book) {
– cid
– attributes return [Link]("name").toLowerCase();
– changed });
– defaults
– toJSON var randomThree = [Link](3);
– sync
– fetch
– save add [Link](models, [options])
– destroy
– Underscore Methods (9) Add a model (or an array of models) to the collection, firing an "add" event for each
– validate model, and an "update" event afterwards. If a model property is defined, you may also
– validationError
pass raw attributes objects, and have them be vivified as instances of the model.
– isValid
– url
Returns the added (or preexisting, if duplicate) models. Pass {at: index} to splice the
– urlRoot model into the collection at the specified index. If you're adding models to the
– parse collection that are already in the collection, they'll be ignored, unless you pass {merge:
– clone
true}, in which case their attributes will be merged into the corresponding models,
– isNew
– hasChanged firing any appropriate "change" events.
– changedAttributes
– previous
var ships = new [Link];
– previousAttributes

[Link]("add", function(ship) {
Collection
alert("Ahoy " + [Link]("name") + "!");
– extend
});
– model
– modelId
[Link]([
– constructor / initialize
{name: "Flying Dutchman"},
– models
– toJSON {name: "Black Pearl"}
– sync ]);
– Underscore Methods (46)
– add
Note that adding the same model (a model with the same id) to a collection more than once
– remove
is a no-op.
– reset
– set
– get
– at
remove [Link](models, [options])
– push Remove a model (or an array of models) from the collection, and return them. Each
– pop
model can be a Model instance, an id string or a JS object, any value acceptable as
– unshift
– shift the id argument of [Link]. Fires a "remove" event for each model, and a
– slice single "update" event afterwards, unless {silent: true} is passed. The model's
– length
index before removal is available to listeners as [Link].
– comparator
– sort
– pluck
– where
reset [Link]([models], [options])
– findWhere Adding and removing models one at a time is all well and good, but sometimes you
– url
have so many models to change that you'd rather just update the collection in bulk. Use
– parse
– clone reset to replace a collection with a new list of models (or attribute hashes), triggering a
– fetch single "reset" event on completion, and without triggering any add or remove events
– create
on any models. Returns the newly-set models. For convenience, within a "reset"
Router event, the list of any previous models is available as [Link].
– extend Pass null for models to empty your Collection with options.
– routes
– constructor / initialize
Here's an example using reset to bootstrap a collection during initial page load, in a
– route
– navigate Rails application:
– execute

<script>
History
var accounts = new [Link];
– start [Link](<%= @accounts.to_json %>);

Sync
</script>

[Link] (1.3.3)
Calling [Link]() without passing any models as arguments will empty the
» GitHub Repository
» Annotated Source entire collection.

Getting Started
‑ Introduction set [Link](models, [options])
– Models and Views
The set method performs a "smart" update of the collection with the passed list of
– Collections
– API Integration
models. If a model in the list isn't yet in the collection it will be added; if the model is
– Rendering already in the collection its attributes will be merged; and if the collection contains any
– Routing models that aren't present in the list, they'll be removed. All of the appropriate "add",
"remove", and "change" events are fired as this happens. Returns the touched
Events
models in the collection. If you'd like to customize the behavior, you can disable it with
– on
– off options: {add: false}, {remove: false}, or {merge: false}.
– trigger
– once
var vanHalen = new [Link]([eddie, alex, stone, roth]);
– listenTo
– stopListening
[Link]([eddie, alex, stone, hagar]);
– listenToOnce
‑ Catalog of Built‑in Events
// Fires a "remove" event for roth, and an "add" event for "hagar".
Model // Updates any of stone, alex, and eddie's attributes that may have
// changed over the years.
– extend
– constructor / initialize
– get
– set get [Link](id)
– escape
Get a model from a collection, specified by an id, a cid, or by passing in a model.
– has
– unset
– clear var book = [Link](110);
– id
– idAttribute
– cid
at [Link](index)
– attributes
– changed Get a model from a collection, specified by index. Useful if your collection is sorted, and
– defaults
if your collection isn't sorted, at will still retrieve models in insertion order. When passed
– toJSON
– sync
a negative index, it will retrieve the model from the back of the collection.
– fetch
– save
– destroy push [Link](model, [options])
– Underscore Methods (9)
Add a model at the end of a collection. Takes the same options as add.
– validate
– validationError
– isValid
– url pop [Link]([options])
– urlRoot Remove and return the last model from a collection. Takes the same options as remove.
– parse
– clone
– isNew
– hasChanged
unshift [Link](model, [options])

– changedAttributes Add a model at the beginning of a collection. Takes the same options as add.
– previous
– previousAttributes

shift [Link]([options])
Collection
– extend
Remove and return the first model from a collection. Takes the same options as remove.
– model
– modelId
– constructor / initialize slice [Link](begin, end)
– models
Return a shallow copy of this collection's models, using the same options as native
– toJSON
– sync Array#slice.
– Underscore Methods (46)
– add
– remove length [Link]
– reset
Like an array, a Collection maintains a length property, counting the number of
– set
– get models it contains.
– at
– push
– pop comparator [Link]
– unshift
– shift By default there is no comparator for a collection. If you define a comparator, it will be
– slice used to maintain the collection in sorted order. This means that as models are added,
– length they are inserted at the correct index in [Link]. A comparator can be
– comparator
defined as a sortBy (pass a function that takes a single argument), as a sort (pass a
– sort
– pluck comparator function that expects two arguments), or as a string indicating the attribute
– where to sort by.
– findWhere
– url
– parse "sortBy" comparator functions take a model and return a numeric or string value by
– clone which the model should be ordered relative to others. "sort" comparator functions take
– fetch
two models, and return -1 if the first model should come before the second, 0 if they
– create
are of the same rank and 1 if the first model should come after. Note that Backbone
Router depends on the arity of your comparator function to determine between the two styles,
– extend so be careful if your comparator function is bound.
– routes
– constructor / initialize
– route Note how even though all of the chapters in this example are added backwards, they
– navigate come out in the proper order:
– execute

History var Chapter = [Link];


var chapters = new [Link];
– start

Sync
[Link] = 'page';

[Link] (1.3.3) [Link](new Chapter({page: 9, title: "The End"}));


» GitHub Repository [Link](new Chapter({page: 5, title: "The Middle"}));
» Annotated Source [Link](new Chapter({page: 1, title: "The Beginning"}));

Getting Started alert([Link]('title'));


‑ Introduction
– Models and Views
Collections with a comparator will not automatically re-sort if you later change model attributes, so you
– Collections
may wish to call sort after changing model attributes that would affect the order.
– API Integration
– Rendering
– Routing
sort [Link]([options])
Events Force a collection to re-sort itself. You don't need to call this under normal
– on circumstances, as a collection with a comparator will sort itself whenever a model is
– off
added. To disable sorting when adding a model, pass {sort: false} to add. Calling
– trigger
– once sort triggers a "sort" event on the collection.
– listenTo
– stopListening
– listenToOnce pluck [Link](attribute)
‑ Catalog of Built‑in Events
Pluck an attribute from each model in the collection. Equivalent to calling map and
Model returning a single attribute from the iterator.
– extend
– constructor / initialize
var stooges = new [Link]([
– get
{name: "Curly"},
– set
{name: "Larry"},
– escape
{name: "Moe"}
– has
]);
– unset
– clear
– id var names = [Link]("name");
– idAttribute
– cid alert([Link](names));
– attributes
– changed
– defaults where [Link](attributes)
– toJSON
– sync Return an array of all the models in a collection that match the passed attributes.
– fetch Useful for simple cases of filter.
– save
– destroy
– Underscore Methods (9) var friends = new [Link]([
– validate {name: "Athos", job: "Musketeer"},
– validationError {name: "Porthos", job: "Musketeer"},
– isValid {name: "Aramis", job: "Musketeer"},
– url {name: "d'Artagnan", job: "Guard"},
– urlRoot ]);
– parse
– clone var musketeers = [Link]({job: "Musketeer"});
– isNew
– hasChanged alert([Link]);
– changedAttributes
– previous
– previousAttributes
findWhere [Link](attributes)

Collection Just like where, but directly returns only the first model in the collection that matches
– extend the passed attributes.
– model
– modelId
– constructor / initialize
url [Link] or [Link]()
– models
– toJSON Set the url property (or function) on a collection to reference its location on the server.
– sync Models within the collection will use url to construct URLs of their own.
– Underscore Methods (46)
– add
– remove var Notes = [Link]({
– reset url: '/notes'
– set });
– get
– at // Or, something more sophisticated:
– push
– pop var Notes = [Link]({
– unshift
url: function() {
– shift
return [Link]() + '/notes';
– slice
}
– length
});
– comparator
– sort
– pluck
– where parse [Link](response, options)
– findWhere
parse is called by Backbone whenever a collection's models are returned by the server,
– url
– parse in fetch. The function is passed the raw response object, and should return the array
– clone of model attributes to be added to the collection. The default implementation is a no-
– fetch op, simply passing through the JSON response. Override this if you need to work with a
– create
preexisting API, or better namespace your responses.
Router
– extend var Tweets = [Link]({
– routes // The Twitter Search API returns tweets under "results".
– constructor / initialize parse: function(response) {
– route return [Link];
– navigate }
– execute });

History
– start clone [Link]()

Sync
Returns a new instance of the collection with an identical list of models.

[Link] (1.3.3)

» GitHub Repository fetch [Link]([options])


» Annotated Source
Fetch the default set of models for this collection from the server, setting them on the
Getting Started collection when they arrive. The options hash takes success and error callbacks
‑ Introduction which will both be passed (collection, response, options) as arguments. When
– Models and Views the model data returns from the server, it uses set to (intelligently) merge the fetched
– Collections
– API Integration
models, unless you pass {reset: true}, in which case the collection will be
– Rendering (efficiently) reset. Delegates to [Link] under the covers for custom persistence
– Routing strategies and returns a jqXHR. The server handler for fetch requests should return a
JSON array of models.
Events
– on
– off [Link] = function(method, model) {
– trigger alert(method + ": " + [Link]);
– once };
– listenTo
– stopListening var accounts = new [Link];
– listenToOnce [Link] = '/accounts';
‑ Catalog of Built‑in Events

[Link]();
Model
– extend
– constructor / initialize The behavior of fetch can be customized by using the available set options. For
– get example, to fetch a collection, getting an "add" event for every new model, and a
– set
"change" event for every changed existing model, without removing anything:
– escape
– has [Link]({remove: false})
– unset
– clear
[Link] options can also be passed directly as fetch options, so to fetch a specific
– id
– idAttribute page of a paginated collection: [Link]({data: {page: 3}})
– cid
– attributes
Note that fetch should not be used to populate collections on page load — all models
– changed
– defaults needed at load time should already be bootstrapped in to place. fetch is intended for
– toJSON lazily-loading models for interfaces that are not needed immediately: for example,
– sync
documents with collections of notes that may be toggled open and closed.
– fetch
– save
– destroy
– Underscore Methods (9)
create [Link](attributes, [options])
– validate Convenience to create a new instance of a model within a collection. Equivalent to
– validationError
instantiating a model with a hash of attributes, saving the model to the server, and
– isValid
– url adding the model to the set after being successfully created. Returns the new model. If
– urlRoot client-side validation failed, the model will be unsaved, with validation errors. In order
– parse
for this to work, you should set the model property of the collection. The create method
– clone
– isNew can accept either an attributes hash or an existing, unsaved model object.
– hasChanged
– changedAttributes
Creating a model will cause an immediate "add" event to be triggered on the
– previous
– previousAttributes collection, a "request" event as the new model is sent to the server, as well as a
"sync" event, once the server has responded with the successful creation of the
Collection model. Pass {wait: true} if you'd like to wait for the server before adding the new
– extend
model to the collection.
– model
– modelId
– constructor / initialize var Library = [Link]({
– models model: Book
– toJSON });
– sync
– Underscore Methods (46) var nypl = new Library;
– add
– remove
var othello = [Link]({
– reset
title: "Othello",
– set
author: "William Shakespeare"
– get
});
– at
– push
– pop
– unshift
– shift [Link]
– slice
– length
Web applications often provide linkable, bookmarkable, shareable URLs for important
– comparator
– sort
locations in the app. Until recently, hash fragments ( #page) were used to provide these
– pluck permalinks, but with the arrival of the History API, it's now possible to use standard
– where URLs ( /page). [Link] provides methods for routing client-side pages, and
– findWhere
connecting them to actions and events. For browsers which don't yet support the
– url
– parse History API, the Router handles graceful fallback and transparent translation to the
– clone fragment version of the URL.
– fetch
– create
During page load, after your application has finished creating all of its routers, be sure
Router to call [Link]() or [Link]({pushState: true})
– extend to route the initial URL.
– routes
– constructor / initialize
– route
extend [Link](properties, [classProperties])
– navigate
– execute Get started by creating a custom router class. Define actions that are triggered when
certain URL fragments are matched, and provide a routes hash that pairs routes to
History
actions. Note that you'll want to avoid using a leading slash in your route definitions:
– start

Sync
var Workspace = [Link]({

[Link] (1.3.3) routes: {


» GitHub Repository "help": "help", // #help
» Annotated Source "search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
Getting Started },
‑ Introduction
– Models and Views help: function() {
– Collections ...
– API Integration },
– Rendering
– Routing search: function(query, page) {
...
Events }
– on
– off });
– trigger
– once
– listenTo
routes [Link]
– stopListening
– listenToOnce The routes hash maps URLs with parameters to functions on your router (or just direct
‑ Catalog of Built‑in Events
function definitions, if you prefer), similar to the View's events hash. Routes can contain

Model parameter parts, :param, which match a single URL component between slashes; and

– extend
splat parts *splat, which can match any number of URL components. Part of a route
– constructor / initialize can be made optional by surrounding it in parentheses (/:optional).
– get
– set
– escape For example, a route of "search/:query/p:page" will match a fragment of
– has #search/obama/p2, passing "obama" and "2" to the action.
– unset
– clear
– id A route of "file/*path" will match #file/folder/[Link], passing
– idAttribute "folder/[Link]" to the action.
– cid
– attributes
– changed A route of "docs/:section(/:subsection)" will match #docs/faq and
– defaults #docs/faq/installing, passing "faq" to the action in the first case, and passing
– toJSON
"faq" and "installing" to the action in the second.
– sync
– fetch
– save A nested optional route of "docs(/:section)(/:subsection)" will match #docs,
– destroy
#docs/faq, and #docs/faq/installing, passing "faq" to the action in the second
– Underscore Methods (9)
– validate case, and passing "faq" and "installing" to the action in the third.
– validationError
– isValid
Trailing slashes are treated as part of the URL, and (correctly) treated as a unique route
– url
– urlRoot when accessed. docs and docs/ will fire different callbacks. If you can't avoid
– parse generating both types of URLs, you can define a "docs(/)" matcher to capture both
– clone
cases.
– isNew
– hasChanged
– changedAttributes When the visitor presses the back button, or enters a URL, and a particular route is
– previous
matched, the name of the action will be fired as an event, so that other objects can
– previousAttributes
listen to the router, and be notified. In the following example, visiting #help/uploading
Collection will fire a route:help event from the router.
– extend
– model
routes: {
– modelId
"help/:page": "help",
– constructor / initialize
"download/*path": "download",
– models
"folder/:name": "openFolder",
– toJSON
– sync "folder/:name-:mode": "openFolder"
– Underscore Methods (46) }
– add
– remove
[Link]("route:help", function(page) {
– reset
...
– set
});
– get
– at
– push
– pop constructor / initialize new Router([options])
– unshift
When creating a new router, you may pass its routes hash directly as an option, if you
– shift
– slice choose. All options will also be passed to your initialize function, if defined.
– length
– comparator
– sort route [Link](route, name, [callback])
– pluck
– where
Manually create a route for the router, The route argument may be a routing string or
– findWhere regular expression. Each matching capture from the route or regular expression will be
– url passed as an argument to the callback. The name argument will be triggered as a
– parse
"route:name" event whenever the route is matched. If the callback argument is
– clone
– fetch omitted router[name] will be used instead. Routes added later may override
– create previously declared routes.

Router
initialize: function(options) {
– extend
– routes
// Matches #page/10, passing "10"
– constructor / initialize
– route [Link]("page/:number", "page", function(number){ ... });
– navigate
– execute // Matches /117-a/b/c/open, passing "117-a/b/c" to [Link]
[Link](/^(.*?)\/open$/, "open");
History
– start },

Sync
open: function(id) { ... }

[Link] (1.3.3)

» GitHub Repository navigate [Link](fragment, [options])


» Annotated Source
Whenever you reach a point in your application that you'd like to save as a URL, call
Getting Started navigate in order to update the URL. If you also wish to call the route function, set the
‑ Introduction trigger option to true. To update the URL without creating an entry in the browser's
– Models and Views history, set the replace option to true.
– Collections
– API Integration
– Rendering openPage: function(pageNumber) {
– Routing [Link](pageNumber).open();
[Link]("page/" + pageNumber);
Events }
– on
– off # Or ...
– trigger
– once [Link]("help/troubleshooting", {trigger: true});
– listenTo
– stopListening # Or ...
– listenToOnce
‑ Catalog of Built‑in Events [Link]("help/troubleshooting", {trigger: true, replace: true});

Model
– extend execute [Link](callback, args, name)
– constructor / initialize
– get This method is called internally within the router, whenever a route matches and its
– set corresponding callback is about to be executed. Return false from execute to cancel
– escape
the current transition. Override it to perform custom parsing or wrapping of your routes,
– has
– unset for example, to parse query strings before handing them to your route callback, like so:
– clear
– id
var Router = [Link]({
– idAttribute
execute: function(callback, args, name) {
– cid
if (!loggedIn) {
– attributes
goToLogin();
– changed
– defaults
return false;
– toJSON }
– sync [Link](parseQueryString([Link]()));
– fetch if (callback) [Link](this, args);
– save }
– destroy });
– Underscore Methods (9)
– validate
– validationError
– isValid [Link]
– url
– urlRoot
– parse History serves as a global router (per frame) to handle hashchange events or
– clone pushState, match the appropriate route, and trigger callbacks. You shouldn't ever
– isNew have to create one of these yourself since [Link] already contains one.
– hasChanged
– changedAttributes
– previous pushState support exists on a purely opt-in basis in Backbone. Older browsers that
– previousAttributes
don't support pushState will continue to use hash-based URL fragments, and if a hash
Collection URL is visited by a pushState-capable browser, it will be transparently upgraded to the
– extend
true URL. Note that using real URLs requires your web server to be able to correctly
– model render those pages, so back-end changes are required as well. For example, if you
– modelId have a route of /documents/100, your web server must be able to serve that page, if
– constructor / initialize
the browser visits that URL directly. For full search-engine crawlability, it's best to have
– models
– toJSON the server generate the complete HTML for the page ... but if it's a web application, just
– sync rendering the same content you would have for the root URL, and filling in the rest with
– Underscore Methods (46)
Backbone Views and JavaScript works fine.
– add
– remove
– reset
– set
start [Link]([options])
– get When all of your Routers have been created, and all of the routes are set up properly,
– at
call [Link]() to begin monitoring hashchange events, and
– push
– pop dispatching routes. Subsequent calls to [Link]() will throw an
– unshift error, and [Link] is a boolean value indicating whether it has
– shift
already been called.
– slice
– length
– comparator To indicate that you'd like to use HTML5 pushState support in your application, use
– sort
[Link]({pushState: true}). If you'd like to use pushState, but
– pluck
– where have browsers that don't support it natively use full page refreshes instead, you can
– findWhere add {hashChange: false} to the options.
– url
– parse
– clone If your application is not being served from the root url / of your domain, be sure to tell
– fetch History where the root really is, as an option: [Link]({pushState:
– create
true, root: "/public/search/"})

Router
– extend When called, if a route succeeds with a match for the current URL,
– routes [Link]() returns true. If no defined route matches the current
– constructor / initialize
URL, it returns false.
– route
– navigate
– execute If the server has already rendered the entire page, and you don't want the initial route to
trigger when starting History, pass silent: true.
History
– start
Because hash-based history in Internet Explorer relies on an <iframe>, be sure to call
Sync
start() only after the DOM is ready.

[Link] (1.3.3)
$(function(){
» GitHub Repository
new WorkspaceRouter();
» Annotated Source
new HelpPaneRouter();
Getting Started [Link]({pushState: true});
});
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering [Link]
– Routing
[Link] is the function that Backbone calls every time it attempts to read or
Events
save a model to the server. By default, it uses [Link] to make a RESTful JSON
– on
request and returns a jqXHR. You can override it in order to use a different persistence
– off
– trigger strategy, such as WebSockets, XML transport, or Local Storage.
– once
– listenTo
– stopListening
The method signature of [Link] is sync(method, model, [options])
– listenToOnce
‑ Catalog of Built‑in Events method – the CRUD method ( "create", "read", "update", or "delete")

Model model – the model to be saved (or collection to be read)


– extend
options – success and error callbacks, and all other jQuery request options
– constructor / initialize
– get
– set With the default implementation, when [Link] sends up a request to save a
– escape
model, its attributes will be passed, serialized as JSON, and sent in the HTTP body with
– has
– unset content-type application/json. When returning a JSON response, send down the
– clear attributes of the model that have been changed by the server, and need to be updated
– id on the client. When responding to a "read" request from a collection
– idAttribute
(Collection#fetch), send down an array of model attribute objects.
– cid
– attributes
– changed
Whenever a model or collection begins a sync with the server, a "request" event is
– defaults
– toJSON
emitted. If the request completes successfully you'll get a "sync" event, and an
– sync "error" event if not.
– fetch
– save
– destroy The sync function may be overridden globally as [Link], or at a finer-grained
– Underscore Methods (9) level, by adding a sync function to a Backbone collection or to an individual model.
– validate
– validationError
– isValid The default sync handler maps CRUD to REST like so:
– url
– urlRoot
create → POST /collection
– parse
– clone read → GET /collection[/id]
– isNew
– hasChanged update → PUT /collection/id
– changedAttributes
patch → PATCH /collection/id
– previous
– previousAttributes delete → DELETE /collection/id

Collection
– extend
As an example, a Rails 4 handler responding to an "update" call from Backbone might
– model look like this:
– modelId
– constructor / initialize
def update
– models
– toJSON account = [Link] params[:id]
– sync permitted = [Link](:account).permit(:name, :otherparam)
– Underscore Methods (46) account.update_attributes permitted
– add render :json => account
– remove end
– reset
– set
– get One more tip for integrating Rails versions prior to 3.1 is to disable the default
– at namespacing for to_json calls on models by setting
– push
ActiveRecord::Base.include_root_in_json = false
– pop
– unshift
– shift
– slice
ajax [Link] = function(request) { ... };

– length If you want to use a custom AJAX function, or your endpoint doesn't support the
– comparator
[Link] API and you need to tweak things, you can do so by setting
– sort
– pluck [Link].
– where
– findWhere
– url emulateHTTP [Link] = true
– parse
If you want to work with a legacy web server that doesn't support Backbone's default
– clone
– fetch REST/HTTP approach, you may choose to turn on [Link]. Setting this
– create option will fake PUT, PATCH and DELETE requests with a HTTP POST, setting the X-
HTTP-Method-Override header with the true method. If emulateJSON is also on, the
Router
true method will be passed as an additional _method parameter.
– extend
– routes
– constructor / initialize [Link] = true;
– route
– navigate [Link](); // POST to "/collection/id", with "_method=PUT" + header.
– execute

History
emulateJSON [Link] = true
– start
If you're working with a legacy web server that can't handle requests encoded as
Sync
application/json, setting [Link] = true; will cause the JSON to
be serialized under a model parameter, and the request to be made with a
[Link] (1.3.3)
application/x-www-form-urlencoded MIME type, as if from an HTML form.
» GitHub Repository
» Annotated Source

Getting Started
[Link]
‑ Introduction
– Models and Views
– Collections Backbone views are almost more convention than they are code — they don't
– API Integration determine anything about your HTML or CSS for you, and can be used with any
– Rendering
JavaScript templating library. The general idea is to organize your interface into logical
– Routing
views, backed by models, each of which can be updated independently when the
Events model changes, without having to redraw the page. Instead of digging into a JSON
– on object, looking up an element in the DOM, and updating the HTML by hand, you can
– off
bind your view's render function to the model's "change" event — and now
– trigger
– once
everywhere that model data is displayed in the UI, it is always immediately up to date.
– listenTo
– stopListening
– listenToOnce extend [Link](properties, [classProperties])
‑ Catalog of Built‑in Events
Get started with views by creating a custom view class. You'll want to override the
Model render function, specify your declarative events, and perhaps the tagName,
– extend className, or id of the View's root element.
– constructor / initialize
– get
var DocumentRow = [Link]({
– set
– escape
tagName: "li",
– has
– unset
– clear className: "document-row",
– id
– idAttribute events: {
– cid "click .icon": "open",
– attributes "click .[Link]": "openEditDialog",
– changed "click .[Link]": "destroy"
– defaults },
– toJSON
– sync initialize: function() {
– fetch [Link]([Link], "change", [Link]);
– save },
– destroy
– Underscore Methods (9)
render: function() {
– validate
...
– validationError
}
– isValid
– url
– urlRoot
});
– parse
– clone
Properties like tagName, id, className, el, and events may also be defined as a
– isNew
– hasChanged function, if you want to wait to define them until runtime.
– changedAttributes
– previous
– previousAttributes constructor / initialize new View([options])

Collection There are several special options that, if passed, will be attached directly to the view:
model, collection, el, id, className, tagName, attributes and events. If the
– extend
– model view defines an initialize function, it will be called when the view is first created. If you'd
– modelId like to create a view that references an element already in the DOM, pass in the element
– constructor / initialize
as an option: new View({el: existingElement})
– models
– toJSON
– sync var doc = [Link]();
– Underscore Methods (46)
– add new DocumentRow({
– remove
model: doc,
– reset
id: "document-row-" + [Link]
– set
});
– get
– at
– push
– pop el [Link]
– unshift
All views have a DOM element at all times (the el property), whether they've already
– shift
– slice
been inserted into the page or not. In this fashion, views can be rendered at any time,
– length and inserted into the DOM all at once, in order to get high-performance UI rendering
– comparator with as few reflows and repaints as possible.
– sort
– pluck
– where [Link] can be resolved from a DOM selector string or an Element; otherwise it will be
– findWhere created from the view's tagName, className, id and attributes properties. If none
– url
– parse
are set, [Link] is an empty div, which is often just fine. An el reference may also be
– clone passed in to the view's constructor.
– fetch
– create
var ItemView = [Link]({
Router tagName: 'li'
});
– extend
– routes
var BodyView = [Link]({
– constructor / initialize
el: 'body'
– route
– navigate
});
– execute
var item = new ItemView();
History var body = new BodyView();

– start
alert([Link] + ' ' + [Link]);
Sync
$el view.$el
[Link] (1.3.3) A cached jQuery object for the view's element. A handy reference instead of re-
» GitHub Repository wrapping the DOM element all the time.
» Annotated Source

Getting Started view.$[Link]();


‑ Introduction
– Models and Views listView.$[Link]([Link]);
– Collections
– API Integration
– Rendering setElement [Link](element)
– Routing
If you'd like to apply a Backbone view to a different DOM element, use setElement,
Events which will also create the cached $el reference and move the view's delegated events
– on from the old element to the new one.
– off
– trigger
– once attributes [Link]
– listenTo
– stopListening A hash of attributes that will be set as HTML DOM element attributes on the view's el
– listenToOnce (id, class, data-properties, etc.), or a function that returns such a hash.
‑ Catalog of Built‑in Events

Model $ (jQuery) view.$(selector)


– extend
If jQuery is included on the page, each view has a $ function that runs queries scoped
– constructor / initialize
– get within the view's element. If you use this scoped jQuery function, you don't have to use
– set model ids as part of your query to pull out specific elements in a list, and can rely much
– escape
more on HTML class attributes. It's equivalent to running: view.$[Link](selector)
– has
– unset
– clear [Link] = [Link]({
– id serialize : function() {
– idAttribute return {
– cid
title: this.$(".title").text(),
– attributes
start: this.$(".start-page").text(),
– changed
end: this.$(".end-page").text()
– defaults
};
– toJSON
}
– sync
});
– fetch
– save
– destroy
– Underscore Methods (9) template [Link]([data])
– validate
While templating for a view isn't a function provided directly by Backbone, it's often a
– validationError
– isValid nice convention to define a template function on your views. In this way, when
– url rendering your view, you have convenient access to instance data. For example, using
– urlRoot
Underscore templates:
– parse
– clone
– isNew var LibraryView = [Link]({
– hasChanged template: _.template(...)
– changedAttributes });
– previous
– previousAttributes

Collection
render [Link]()

– extend The default implementation of render is a no-op. Override this function with your code
– model that renders the view template from model data, and updates [Link] with the new
– modelId
HTML. A good convention is to return this at the end of render to enable chained
– constructor / initialize
– models calls.
– toJSON
– sync
var Bookmark = [Link]({
– Underscore Methods (46)
template: _.template(...),
– add
render: function() {
– remove
this.$[Link]([Link]([Link]));
– reset
return this;
– set
– get }
– at });
– push
– pop
Backbone is agnostic with respect to your preferred method of HTML templating. Your
– unshift
– shift render function could even munge together an HTML string, or use
– slice [Link] to generate a DOM tree. However, we suggest choosing a
– length
nice JavaScript templating library. [Link], Haml-js, and Eco are all fine
– comparator
– sort alternatives. Because [Link] is already on the page, _.template is available, and
– pluck is an excellent choice if you prefer simple interpolated-JavaScript style templates.
– where
– findWhere
– url Whatever templating strategy you end up with, it's nice if you never have to put strings
– parse of HTML in your JavaScript. At DocumentCloud, we use Jammit in order to package up
– clone
JavaScript templates stored in /app/views as part of our main [Link] asset
– fetch
– create package.

Router
– extend
remove [Link]()
– routes Removes a view and its el from the DOM, and calls stopListening to remove any
– constructor / initialize
bound events that the view has listenTo'd.
– route
– navigate
– execute
events [Link] or [Link]()
History The events hash (or method) can be used to specify a set of DOM events that will be
– start
bound to methods on your View through delegateEvents.

Sync
Backbone will automatically attach the event listeners at instantiation time, right before
invoking initialize.
[Link] (1.3.3)

» GitHub Repository
» Annotated Source var ENTER_KEY = 13;
var InputView = [Link]({
Getting Started
‑ Introduction tagName: 'input',
– Models and Views
– Collections events: {
– API Integration "keydown" : "keyAction",
– Rendering },
– Routing
render: function() { ... },
Events
– on keyAction: function(e) {
– off if ([Link] === ENTER_KEY) {
– trigger [Link]({text: this.$[Link]()});
– once }
– listenTo }
– stopListening });
– listenToOnce
‑ Catalog of Built‑in Events

Model
delegateEvents delegateEvents([events])

– extend Uses jQuery's on function to provide declarative callbacks for DOM events within a
– constructor / initialize view. If an events hash is not passed directly, uses [Link] as the source. Events
– get
are written in the format {"event selector": "callback"}. The callback may be
– set
– escape either the name of a method on the view, or a direct function body. Omitting the
– has selector causes the event to be bound to the view's root element ( [Link]). By
– unset default, delegateEvents is called within the View's constructor for you, so if you have
– clear
– id
a simple events hash, all of your DOM events will always already be connected, and
– idAttribute you will never have to call this function yourself.
– cid
– attributes
– changed
The events property may also be defined as a function that returns an events hash, to
– defaults make it easier to programmatically define your events, as well as inherit them from
– toJSON parent views.
– sync
– fetch
– save Using delegateEvents provides a number of advantages over manually using jQuery to
– destroy bind events to child elements during render. All attached callbacks are bound to the
– Underscore Methods (9)
– validate
view before being handed off to jQuery, so when the callbacks are invoked, this
– validationError continues to refer to the view object. When delegateEvents is run again, perhaps with
– isValid a different events hash, all callbacks are removed and delegated afresh — useful for
– url
views which need to behave differently when in different modes.
– urlRoot
– parse
– clone A single-event version of delegateEvents is available as delegate. In fact,
– isNew
delegateEvents is simply a multi-event wrapper around delegate. A counterpart to
– hasChanged
– changedAttributes undelegateEvents is available as undelegate.
– previous
– previousAttributes
A view that displays a document in a search result might look something like this:
Collection
– extend var DocumentView = [Link]({
– model
– modelId events: {
– constructor / initialize "dblclick" : "open",
– models "click .[Link]" : "select",
– toJSON "contextmenu .[Link]" : "showMenu",
– sync
"click .show_notes" : "toggleNotes",
– Underscore Methods (46)
"click .title .lock" : "editAccessLevel",
– add
"mouseover .title .date" : "showTooltip"
– remove
},
– reset
– set
– get
render: function() {
– at this.$[Link]([Link]([Link]));
– push return this;
– pop },
– unshift
– shift open: function() {
– slice [Link]([Link]("viewer_url"));
– length },
– comparator
– sort select: function() {
– pluck [Link]({selected: true});
– where },
– findWhere
– url
...
– parse
– clone
});
– fetch
– create

Router undelegateEvents undelegateEvents()

– extend Removes all of the view's delegated events. Useful if you want to disable or remove a
– routes
view from the DOM temporarily.
– constructor / initialize
– route
– navigate
– execute
Utility
History
– start [Link]flict var backbone = [Link]();

Sync
Returns the Backbone object back to its original value. You can use the return value of
[Link]() to keep a local reference to Backbone. Useful for embedding
[Link] (1.3.3)
Backbone on third-party websites, where you don't want to clobber the existing
» GitHub Repository
» Annotated Source Backbone.

Getting Started
var localBackbone = [Link]();
‑ Introduction var model = [Link](...);
– Models and Views
– Collections
– API Integration
– Rendering
Backbone.$ Backbone.$ = $;

– Routing If you have multiple copies of jQuery on the page, or simply want to tell Backbone to
use a particular object as its DOM / Ajax library, this is the property for you.
Events
– on
– off Backbone.$ = require('jquery');
– trigger
– once
– listenTo
– stopListening F.A.Q.
– listenToOnce
‑ Catalog of Built‑in Events
Why use Backbone, not [other framework X]?
Model
If your eye hasn't already been caught by the adaptability and elan on display in the
– extend
– constructor / initialize
above list of examples, we can get more specific: [Link] aims to provide the
– get common foundation that data-rich web applications with ambitious interfaces require —
– set while very deliberately avoiding painting you into a corner by making any decisions that
– escape
you're better equipped to make yourself.
– has
– unset
– clear The focus is on supplying you with helpful methods to manipulate and query your data, not on
– id HTML widgets or reinventing the JavaScript object model.
– idAttribute
– cid Backbone does not force you to use a single template engine. Views can bind to HTML
– attributes constructed in your favorite way.
– changed
It's smaller. There are fewer kilobytes for your browser or phone to download, and less
– defaults
conceptual surface area. You can read and understand the source in an afternoon.
– toJSON
– sync It doesn't depend on stuffing application logic into your HTML. There's no embedded
– fetch JavaScript, template logic, or binding hookup code in data- or ng- attributes, and no need
– save
to invent your own HTML tags.
– destroy
– Underscore Methods (9) Synchronous events are used as the fundamental building block, not a difficult-to-reason-
– validate about run loop, or by constantly polling and traversing your data structures to hunt for
– validationError changes. And if you want a specific event to be asynchronous and aggregated, no problem.
– isValid
– url Backbone scales well, from embedded widgets to massive apps.
– urlRoot
Backbone is a library, not a framework, and plays well with others. You can embed Backbone
– parse
widgets in Dojo apps without trouble, or use Backbone models as the data backing for D3
– clone
visualizations (to pick two entirely random examples).
– isNew
– hasChanged "Two-way data-binding" is avoided. While it certainly makes for a nifty demo, and works for
– changedAttributes the most basic CRUD, it doesn't tend to be terribly useful in your real-world app. Sometimes
– previous you want to update on every keypress, sometimes on blur, sometimes when the panel is
– previousAttributes
closed, and sometimes when the "save" button is clicked. In almost all cases, simply
serializing the form to JSON is faster and easier. All that aside, if your heart is set, go for it.
Collection
– extend There's no built-in performance penalty for choosing to structure your code with Backbone.
– model And if you do want to optimize further, thin models and templates with flexible granularity
– modelId make it easy to squeeze every last drop of potential performance out of, say, IE8.
– constructor / initialize
– models
– toJSON There's More Than One Way To Do It
– sync
– Underscore Methods (46)
It's common for folks just getting started to treat the examples listed on this page as
– add some sort of gospel truth. In fact, [Link] is intended to be fairly agnostic about
– remove many common patterns in client-side code. For example...
– reset
– set
– get References between Models and Views can be handled several ways. Some people
– at like to have direct pointers, where views correspond 1:1 with models ( [Link] and
– push
[Link]). Others prefer to have intermediate "controller" objects that orchestrate
– pop
– unshift the creation and organization of views into a hierarchy. Others still prefer the evented
– shift approach, and always fire events instead of calling methods directly. All of these styles
– slice
work well.
– length
– comparator
– sort Batch operations on Models are common, but often best handled differently
– pluck
depending on your server-side setup. Some folks don't mind making individual Ajax
– where
– findWhere requests. Others create explicit resources for RESTful batch operations:
– url /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the
– parse
creation of "changeset" requests:
– clone
– fetch
– create {
"create": [array of models to create]
Router "update": [array of models to update]
– extend "destroy": [array of model ids to destroy]
– routes }
– constructor / initialize
– route
– navigate Feel free to define your own events. [Link] is designed so that you can
– execute mix it in to any JavaScript object or prototype. Since you can use any string as an
event, it's often handy to bind and trigger your own custom events:
History
[Link]("selected:true") or [Link]("editing")
– start

Sync
Render the UI as you see fit. Backbone is agnostic as to whether you use Underscore
templates, [Link], direct DOM manipulation, server-side rendered snippets of
[Link] (1.3.3)
HTML, or jQuery UI in your render function. Sometimes you'll create a view for each
» GitHub Repository
» Annotated Source model ... sometimes you'll have a view that renders thousands of models at once, in a
tight loop. Both can be appropriate in the same app, depending on the quantity of data
Getting Started involved, and the complexity of the UI.
‑ Introduction
– Models and Views
– Collections Nested Models & Collections
– API Integration
– Rendering It's common to nest collections inside of models with Backbone. For example, consider
– Routing a Mailbox model that contains many Message models. One nice pattern for handling
this is have a [Link] collection for each mailbox, enabling the lazy-loading of
Events
messages, when the mailbox is first opened ... perhaps with MessageList views
– on
– off listening for "add" and "remove" events.
– trigger
– once
var Mailbox = [Link]({
– listenTo
– stopListening
initialize: function() {
– listenToOnce
‑ Catalog of Built‑in Events
[Link] = new Messages;
[Link] = '/mailbox/' + [Link] + '/messages';
Model [Link]("reset", [Link]);
},
– extend
– constructor / initialize
– get
...
– set
– escape });
– has
– unset var inbox = new Mailbox;
– clear
– id // And then, when the Inbox is opened:
– idAttribute
– cid [Link]({reset: true});
– attributes
– changed
– defaults If you're looking for something more opinionated, there are a number of Backbone
– toJSON plugins that add sophisticated associations among models, available on the wiki.
– sync
– fetch
– save Backbone doesn't include direct support for nested models and collections or "has
– destroy many" associations because there are a number of good patterns for modeling
– Underscore Methods (9)
– validate
structured data on the client side, and Backbone should provide the foundation for
– validationError implementing any of them. You may want to…
– isValid
– url
Mirror an SQL database's structure, or the structure of a NoSQL database.
– urlRoot
– parse Use models with arrays of "foreign key" ids, and join to top level collections (a-la tables).
– clone
– isNew For associations that are numerous, use a range of ids instead of an explicit list.
– hasChanged
Avoid ids, and use direct references, creating a partial object graph representing your data set.
– changedAttributes
– previous Lazily load joined models from the server, or lazily deserialize nested models from JSON
– previousAttributes documents.

Collection
– extend Loading Bootstrapped Models
– model
– modelId
When your app first loads, it's common to have a set of initial models that you know
– constructor / initialize you're going to need, in order to render the page. Instead of firing an extra AJAX
– models request to fetch them, a nicer pattern is to have their data already bootstrapped into the
– toJSON
page. You can then use reset to populate your collections with the initial data. At
– sync
– Underscore Methods (46) DocumentCloud, in the ERB template for the workspace, we do something along these
– add lines:
– remove
– reset
– set <script>
– get var accounts = new [Link];
– at [Link](<%= @accounts.to_json %>);
– push var projects = new [Link];
– pop [Link](<%= @projects.to_json(:collaborators => true) %>);
– unshift </script>
– shift
– slice
– length You have to escape </ within the JSON string, to prevent javascript injection attacks.
– comparator
– sort
– pluck Extending Backbone
– where
– findWhere Many JavaScript libraries are meant to be insular and self-enclosed, where you interact
– url with them by calling their public API, but never peek inside at the guts. [Link] is
– parse not that kind of library.
– clone
– fetch
– create Because it serves as a foundation for your application, you're meant to extend and
enhance it in the ways you see fit — the entire source code is annotated to make this
Router
easier for you. You'll find that there's very little there apart from core functions, and
– extend
– routes
most of those can be overridden or augmented should you find the need. If you catch
– constructor / initialize yourself adding methods to [Link], or creating your own base
– route subclass, don't worry — that's how things are supposed to work.
– navigate
– execute

History
How does Backbone relate to "traditional" MVC?
– start Different implementations of the Model-View-Controller pattern tend to disagree about
the definition of a controller. If it helps any, in Backbone, the View class can also be
Sync
thought of as a kind of controller, dispatching events that originate from the UI, with the
HTML template serving as the true view. We call it a View because it represents a
[Link] (1.3.3)
logical chunk of UI, responsible for the contents of a single DOM element.
» GitHub Repository
» Annotated Source
Comparing the overall structure of Backbone to a server-side MVC framework like
Getting Started
Rails, the pieces line up like so:
‑ Introduction
– Models and Views
– Collections [Link] – Like a Rails model minus the class methods. Wraps a row of data in
– API Integration business logic.
– Rendering
– Routing
[Link] – A group of models on the client-side, with sorting/filtering/aggregation
logic.
Events [Link] – Rails [Link] + Rails controller actions. Maps URLs to functions.
– on
– off [Link] – A logical, re-usable piece of UI. Often, but not always, associated with a
– trigger model.
– once
Client-side Templates – Rails .[Link] views, rendering a chunk of HTML.
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events Binding "this"
Perhaps the single most common JavaScript "gotcha" is the fact that when you pass a
Model
function as a callback, its value for this is lost. When dealing with events and
– extend
– constructor / initialize
callbacks in Backbone, you'll often find it useful to rely on listenTo or the optional
– get context argument that many of Underscore and Backbone's methods use to specify
– set the this that will be used when the callback is later invoked. (See _.each, _.map, and
– escape
[Link], to name a few). View events are automatically bound to the view's context for
– has
– unset you. You may also find it helpful to use _.bind and _.bindAll from [Link].
– clear
– id
var MessageList = [Link]({
– idAttribute
– cid
initialize: function() {
– attributes
– changed var messages = [Link];
– defaults [Link]("reset", [Link], this);
– toJSON [Link]("add", [Link], this);
– sync [Link]("remove", [Link], this);
– fetch
– save [Link]([Link], this);
– destroy }
– Underscore Methods (9)
– validate });
– validationError
– isValid // Later, in the app...
– url
– urlRoot
[Link](newMessage);
– parse
– clone
– isNew
– hasChanged Working with Rails
– changedAttributes [Link] was originally extracted from a Rails application; getting your client-side
– previous
(Backbone) Models to sync correctly with your server-side (Rails) Models is painless,
– previousAttributes
but there are still a few things to be aware of.
Collection
– extend
By default, Rails versions prior to 3.1 add an extra layer of wrapping around the JSON
– model
– modelId
representation of models. You can disable this wrapping by setting:
– constructor / initialize
– models
ActiveRecord::Base.include_root_in_json = false
– toJSON
– sync
– Underscore Methods (46) ... in your configuration. Otherwise, override parse to pull model attributes out of the
– add
wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations of models,
– remove
– reset where by default Rails expects namespaced attributes. You can have your controllers
– set filter attributes directly from params, or you can override toJSON in Backbone to add
– get
the extra wrapping Rails expects.
– at
– push
– pop
– unshift
– shift
Examples
– slice
– length The list of examples that follows, while long, is not exhaustive. If you've worked on an
– comparator
app that uses Backbone, please add it to the wiki page of Backbone apps.
– sort
– pluck
– where Jérôme Gravel-Niquet has contributed a Todo List application that is bundled in the
– findWhere
repository as Backbone example. If you're wondering where to get started with
– url
– parse Backbone in general, take a moment to read through the annotated source. The app
– clone uses a LocalStorage adapter to transparently save all of your todos within your browser,
– fetch instead of sending them to a server. Jérôme also has a version hosted at
– create
[Link].
Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Todos
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape DocumentCloud
– has
– unset
The DocumentCloud workspace is built on [Link], with Documents, Projects,
– clear
– id Notes, and Accounts all as Backbone models and collections. If you're interested in
– idAttribute history — both [Link] and [Link] were originally extracted from the
– cid
DocumentCloud codebase, and packaged into standalone JS libraries.
– attributes
– changed
– defaults
– toJSON
DocumentCloud Workspace
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset USA Today
– set
– get
– at USA Today takes advantage of the modularity of Backbone's data/model lifecycle —
– push which makes it simple to create, inherit, isolate, and link application objects — to keep
– pop
the codebase both manageable and efficient. The new website also makes heavy use of
– unshift
– shift the Backbone Router to control the page for both pushState-capable and legacy
– slice browsers. Finally, the team took advantage of Backbone's Event module to create a
– length
PubSub API that allows third parties and analytics packages to hook into the heart of
– comparator
– sort
the app.
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
USA Today
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid Rdio
– attributes
– changed
– defaults
New Rdio was developed from the ground up with a component based framework
– toJSON based on [Link]. Every component on the screen is dynamically loaded and
– sync rendered, with data provided by the Rdio API. When changes are pushed, every
– fetch
component can update itself without reloading the page or interrupting the user's
– save
– destroy music. All of this relies on Backbone's views and models, and all URL routing is handled
– Underscore Methods (9) by Backbone's Router. When data changes are signaled in realtime, Backbone's Events
– validate
notify the interested components in the data changes. Backbone forms the core of the
– validationError
– isValid new, dynamic, realtime Rdio web and desktop applications.
– url
– urlRoot
– parse
– clone Rdio
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop Hulu
– unshift
– shift
– slice Hulu used [Link] to build its next generation online video experience. With
– length Backbone as a foundation, the web interface was rewritten from scratch so that all page
– comparator
content can be loaded dynamically with smooth transitions as you navigate. Backbone
– sort
– pluck makes it easy to move through the app quickly without the reloading of scripts and
– where embedded videos, while also offering models and collections for additional data
– findWhere manipulation support.
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Hulu
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has Quartz
– unset
– clear
– id Quartz sees itself as a digitally native news outlet for the new global economy. Because
– idAttribute Quartz believes in the future of open, cross-platform web applications, they selected
– cid
Backbone and Underscore to fetch, sort, store, and display content from a custom
– attributes
– changed
WordPress API. Although [Link] uses responsive design for phone, tablet, and
– defaults desktop browsers, it also takes advantage of Backbone events and views to render
– toJSON device-specific templates in some cases.
– sync
– fetch
– save
– destroy Quartz
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove Earth
– reset
– set [Link] displays real-time weather conditions on an interactive animated
– get
– at
globe, and Backbone provides the foundation upon which all of the site's components
– push are built. Despite the presence of several other javascript libraries, Backbone's non-
– pop opinionated design made it effortless to mix-in the Events functionality used for
– unshift
distributing state changes throughout the page. When the decision was made to switch
– shift
– slice to Backbone, large blocks of custom logic simply disappeared.
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Earth
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid
– attributes
– changed
– defaults Vox
– toJSON
– sync
– fetch
Vox Media, the publisher of SB Nation, The Verge, Polygon, Eater, Racked, Curbed, and
– save [Link], uses Backbone throughout Chorus, its home-grown publishing platform.
– destroy Backbone powers the liveblogging platform and commenting system used across all
– Underscore Methods (9)
Vox Media properties; Coverage, an internal editorial coordination tool; SB Nation Live,
– validate
– validationError a live event coverage and chat tool; and Vox Cards, [Link]'s highlighter-and-index-
– isValid card inspired app for providing context about the news.
– url
– urlRoot
– parse
– clone Vox
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
– shift
– slice
– length Gawker Media
– comparator
– sort
– pluck
Kinja is Gawker Media's publishing platform designed to create great stories by
– where breaking down the lines between the traditional roles of content creators and
– findWhere consumers. Everyone — editors, readers, marketers — have access to the same tools
– url
to engage in passionate discussion and pursue the truth of the story. Sharing,
– parse
– clone recommending, and following within the Kinja ecosystem allows for improved
– fetch information discovery across all the sites.
– create

Router Kinja is the platform behind Gawker, Gizmodo, Lifehacker, io9 and other Gawker Media
– extend blogs. [Link] underlies the front-end application code that powers everything
– routes from user authentication to post authoring, commenting, and even serving ads. The
– constructor / initialize
JavaScript stack includes [Link] and jQuery, with some plugins, all loaded with
– route
– navigate RequireJS. Closure templates are shared between the Play! Framework based Scala
– execute application and Backbone views, and the responsive layout is done with the Foundation
framework using SASS.
History
– start

Sync
Gawker
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
Flow
– id
– idAttribute MetaLab used [Link] to create Flow, a task management app for teams. The
– cid
workspace relies on [Link] to construct task views, activities, accounts, folders,
– attributes
– changed projects, and tags. You can see the internals under [Link].
– defaults
– toJSON
– sync
– fetch Flow
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
Gilt Groupe
– set
– get Gilt Groupe uses [Link] to build multiple applications across their family of sites.
– at
Gilt's mobile website uses Backbone and [Link] to create a blazing-fast shopping
– push
– pop experience for users on-the-go, while Gilt Live combines Backbone with WebSockets to
– unshift display the items that customers are buying in real-time. Gilt's search functionality also
– shift uses Backbone to filter and sort products efficiently by moving those actions to the
– slice
client-side.
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Gilt Groupe
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has Enigma
– unset
– clear
Enigma is a portal amassing the largest collection of public data produced by
– id
– idAttribute governments, universities, companies, and organizations. Enigma uses Backbone
– cid Models and Collections to represent complex data structures; and Backbone's Router
– attributes
gives Enigma users unique URLs for application states, allowing them to navigate
– changed
– defaults
quickly through the site while maintaining the ability to bookmark pages and navigate
– toJSON forward and backward through their session.
– sync
– fetch
– save
– destroy Enigma
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set NewsBlur
– get
– at
– push NewsBlur is an RSS feed reader and social news network with a fast and responsive UI
– pop that feels like a native desktop app. [Link] was selected for a major rewrite and
– unshift
transition from spaghetti code because of its powerful yet simple feature set, easy
– shift
– slice integration, and large community. If you want to poke around under the hood, NewsBlur
– length is also entirely open-source.
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Newsblur
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model [Link]
– extend
– constructor / initialize
[Link] is the software-as-a-service version of WordPress. It uses [Link]
– get
– set
Models, Collections, and Views in its Notifications system. [Link] was selected
– escape because it was easy to fit into the structure of the application, not the other way around.
– has Automattic (the company behind [Link]) is integrating [Link] into the
– unset
Stats tab and other features throughout the homepage.
– clear
– id
– idAttribute
– cid
– attributes
[Link] Notifications
– changed
– defaults
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
Foursquare
– models
– toJSON Foursquare is a fun little startup that helps you meet up with friends, discover new
– sync
places, and save money. Backbone Models are heavily used in the core JavaScript API
– Underscore Methods (46)
– add layer and Views power many popular features like the homepage map and lists.
– remove
– reset
– set
– get Foursquare
– at
– push
– pop
– unshift
– shift
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start Bitbucket
Sync
Bitbucket is a free source code hosting service for Git and Mercurial. Through its
models and collections, [Link] has proved valuable in supporting Bitbucket's
[Link] (1.3.3)
REST API, as well as newer components such as in-line code comments and approvals
» GitHub Repository
» Annotated Source for pull requests. Mustache templates provide server and client-side rendering, while a
custom Google Closure inspired life-cycle for widgets allows Bitbucket to decorate
Getting Started existing DOM trees and insert new ones.
‑ Introduction
– Models and Views
– Collections
– API Integration Bitbucket
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute Disqus
– cid
– attributes
Disqus chose [Link] to power the latest version of their commenting widget.
– changed
– defaults Backbone’s small footprint and easy extensibility made it the right choice for Disqus’
– toJSON distributed web application, which is hosted entirely inside an iframe and served on
– sync
thousands of large web properties, including IGN, Wired, CNN, MLB, and more.
– fetch
– save
– destroy
– Underscore Methods (9)
Disqus
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
Delicious
– shift
– slice Delicious is a social bookmarking platform making it easy to save, sort, and store
– length bookmarks from across the web. Delicious uses [Link], [Link] and AppCache
– comparator
to build a full-featured MVC web app. The use of Backbone helped the website and
– sort
– pluck mobile apps share a single API service, and the reuse of the model tier made it
– where significantly easier to share code during the recent Delicious redesign.
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Delicious
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events
Khan Academy
Model
– extend Khan Academy is on a mission to provide a free world-class education to anyone
– constructor / initialize
anywhere. With thousands of videos, hundreds of JavaScript-driven exercises, and big
– get
– set plans for the future, Khan Academy uses Backbone to keep frontend code modular and
– escape organized. User profiles and goal setting are implemented with Backbone, jQuery and
– has
Handlebars, and most new feature work is being pushed to the client side, greatly
– unset
– clear increasing the quality of the API.
– id
– idAttribute
– cid
– attributes Khan Academy
– changed
– defaults
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46) IRCCloud
– add
– remove IRCCloud is an always-connected IRC client that you use in your browser — often
– reset
leaving it open all day in a tab. The sleek web interface communicates with an Erlang
– set
– get backend via websockets and the IRCCloud API. It makes heavy use of [Link]
– at events, models, views and routing to keep your IRC conversations flowing in real time.
– push
– pop
– unshift IRCCloud
– shift
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start
Pitchfork
Sync
Pitchfork uses [Link] to power its site-wide audio player, [Link], location
routing, a write-thru page fragment cache, and more. [Link] (and [Link])
[Link] (1.3.3)
helps the team create clean and modular components, move very quickly, and focus on
» GitHub Repository
» Annotated Source the site, not the spaghetti.

Getting Started
‑ Introduction
Pitchfork
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid
– attributes
Spin
– changed
– defaults Spin pulls in the latest news stories from their internal API onto their site using
– toJSON
Backbone models and collections, and a custom sync method. Because the music
– sync
– fetch should never stop playing, even as you click through to different "pages", Spin uses a
– save Backbone router for navigation within the site.
– destroy
– Underscore Methods (9)
– validate
– validationError Spin
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
– shift
– slice
– length
– comparator
– sort
– pluck ZocDoc
– where
– findWhere
– url ZocDoc helps patients find local, in-network doctors and dentists, see their real-time
– parse availability, and instantly book appointments. On the public side, the webapp uses
– clone
[Link] to handle client-side state and rendering in search pages and doctor
– fetch
– create profiles. In addition, the new version of the doctor-facing part of the website is a large
single-page application that benefits from Backbone's structure and modularity.
Router ZocDoc's Backbone classes are tested with Jasmine, and delivered to the end user
– extend
with Cassette.
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
ZocDoc
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset Walmart Mobile
– clear
– id
– idAttribute
Walmart used [Link] to create the new version of their mobile web application
– cid and created two new frameworks in the process. Thorax provides mixins, inheritable
– attributes events, as well as model and collection view bindings that integrate directly with
– changed
Handlebars templates. Lumbar allows the application to be split into modules which
– defaults
– toJSON can be loaded on demand, and creates platform specific builds for the portions of the
– sync web application that are embedded in Walmart's native Android and iOS applications.
– fetch
– save
– destroy Walmart Mobile
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
– shift
– slice Groupon Now!
– length
– comparator
Groupon Now! helps you find local deals that you can buy and use right now. When first
– sort
– pluck developing the product, the team decided it would be AJAX heavy with smooth
– where transitions between sections instead of full refreshes, but still needed to be fully linkable
– findWhere and shareable. Despite never having used Backbone before, the learning curve was
– url
– parse
incredibly quick — a prototype was hacked out in an afternoon, and the team was able
– clone to ship the product in two weeks. Because the source is minimal and understandable, it
– fetch was easy to add several Backbone extensions for Groupon Now!: changing the router
– create
to handle URLs with querystring parameters, and adding a simple in-memory store for
Router caching repeated requests for the same data.
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Groupon Now!
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset Basecamp
– clear
– id
– idAttribute 37Signals chose [Link] to create the calendar feature of its popular project
– cid management software Basecamp. The Basecamp Calendar uses [Link] models
– attributes
and views in conjunction with the Eco templating system to present a polished, highly
– changed
– defaults
interactive group scheduling interface.
– toJSON
– sync
– fetch
– save Basecamp Calendar
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add Slavery Footprint
– remove
– reset
– set Slavery Footprint allows consumers to visualize how their consumption habits are
– get connected to modern-day slavery and provides them with an opportunity to have a
– at
deeper conversation with the companies that manufacture the goods they purchased.
– push
– pop Based in Oakland, California, the Slavery Footprint team works to engage individuals,
– unshift groups, and businesses to build awareness for and create deployable action against
– shift
forced labor, human trafficking, and modern-day slavery through online tools, as well as
– slice
– length
off-line community education and mobilization programs.
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Slavery Footprint
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get Stripe
– set
– escape
Stripe provides an API for accepting credit cards on the web. Stripe's management
– has
– unset interface was recently rewritten from scratch in CoffeeScript using [Link] as the
– clear primary framework, Eco for templates, Sass for stylesheets, and Stitch to package
– id
everything together as CommonJS modules. The new app uses Stripe's API directly for
– idAttribute
– cid the majority of its actions; [Link] models made it simple to map client-side
– attributes models to their corresponding RESTful resources.
– changed
– defaults
– toJSON
– sync Stripe
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync Airbnb
– Underscore Methods (46)
– add
– remove Airbnb uses Backbone in many of its products. It started with Airbnb Mobile Web (built
– reset in six weeks by a team of three) and has since grown to Wish Lists, Match, Search,
– set
Communities, Payments, and Internal Tools.
– get
– at
– push
– pop
– unshift
– shift
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Airbnb
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
SoundCloud Mobile
– clear
– id SoundCloud is the leading sound sharing platform on the internet, and [Link]
– idAttribute
provides the foundation for SoundCloud Mobile. The project uses the public
– cid
– attributes SoundCloud API as a data source (channeled through a nginx proxy), jQuery templates
– changed for the rendering, Qunit and PhantomJS for the testing suite. The JS code, templates
– defaults and CSS are built for the production deployment with various [Link] tools like [Link],
– toJSON
– sync
Jake, jsdom. The [Link] was modified to support the HTML5
– fetch [Link]. [Link] was extended with an additional SessionStorage
– save based cache layer.
– destroy
– Underscore Methods (9)
– validate SoundCloud
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
– shift
– slice
– length
– comparator
– sort [Link]
– pluck
– where
– findWhere [Link] is a place to discover art you'll love. [Link] is built on Rails, using Grape to serve
– url a robust JSON API. The main site is a single page app written in CoffeeScript and uses
– parse Backbone to provide structure around this API. An admin panel and partner CMS have
– clone
– fetch
also been extracted into their own API-consuming Backbone projects.
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
[Link]
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid
– attributes Pandora
– changed
– defaults
– toJSON When Pandora redesigned their site in HTML5, they chose [Link] to help manage
– sync the user interface and interactions. For example, there's a model that represents the
– fetch "currently playing track", and multiple views that automatically update when the current
– save
– destroy
track changes. The station list is a collection, so that when stations are added or
– Underscore Methods (9) changed, the UI stays up to date.
– validate
– validationError
– isValid
– url Pandora
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set
– get
– at Inkling
– push
– pop
– unshift Inkling is a cross-platform way to publish interactive learning content. Inkling for Web
– shift uses [Link] to make hundreds of complex books — from student textbooks to
– slice
travel guides and programming manuals — engaging and accessible on the web.
– length
– comparator Inkling supports WebGL-enabled 3D graphics, interactive assessments, social sharing,
– sort and a system for running practice code right in the book, all within a single page
– pluck
Backbone-driven app. Early on, the team decided to keep the site lightweight by using
– where
– findWhere
only [Link] and raw JavaScript. The result? Complete source code weighing in at
– url a mere 350kb with feature-parity across the iPad, iPhone and web clients. Give it a try
– parse with this excerpt from JavaScript: The Definitive Guide.
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Inkling
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend Code School
– constructor / initialize
– get
Code School courses teach people about various programming topics like CoffeeScript,
– set
– escape CSS, Ruby on Rails, and more. The new Code School course challenge page is built
– has from the ground up on [Link], using everything it has to offer: the router,
– unset
collections, models, and complex event handling. Before, the page was a mess of
– clear
– id jQuery DOM manipulation and manual Ajax calls. [Link] helped introduce a new
– idAttribute way to think about developing an organized front-end application in JavaScript.
– cid
– attributes
– changed
– defaults Code School
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
– set CloudApp
– get
– at CloudApp is simple file and link sharing for the Mac. [Link] powers the web tools
– push
which consume the documented API to manage Drops. Data is either pulled manually
– pop
– unshift or pushed by Pusher and fed to Mustache templates for rendering. Check out the
– shift annotated source code to see the magic.
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
CloudApp
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape SeatGeek
– has
– unset
SeatGeek's stadium ticket maps were originally developed with [Link]. Moving to
– clear
– id [Link] and jQuery helped organize a lot of the UI code, and the increased
– idAttribute structure has made adding features a lot easier. SeatGeek is also in the process of
– cid building a mobile interface that will be [Link] from top to bottom.
– attributes
– changed
– defaults
– toJSON
SeatGeek
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset
Easel
– set
– get
– at Easel is an in-browser, high fidelity web design tool that integrates with your design and
– push development process. The Easel team uses CoffeeScript, [Link] and
– pop
[Link] for their rich visual editor as well as other management functions
– unshift
– shift throughout the site. The structure of Backbone allowed the team to break the complex
– slice problem of building a visual editor into manageable components and still move quickly.
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Easel
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get Jolicloud
– set
– escape
– has
Jolicloud is an open and independent platform and operating system that provides
– unset music playback, video streaming, photo browsing and document editing —
– clear transforming low cost computers into beautiful cloud devices. The new Jolicloud
– id
HTML5 app was built from the ground up using Backbone and talks to the Jolicloud
– idAttribute
– cid Platform, which is based on [Link]. Jolicloud works offline using the HTML5
– attributes AppCache, extends [Link] to store data in IndexedDB or localStorage, and
– changed
communicates with the Joli OS via WebSockets.
– defaults
– toJSON
– sync
– fetch
Jolicloud
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add [Link]
– remove
– reset
– set [Link] provides a space where photographers, artists and designers freely arrange
– get their visual art on virtual walls. [Link] runs on Rails, but does not use much of the
– at
traditional stack, as the entire frontend is designed as a single page web app, using
– push
– pop [Link], Brunch and CoffeeScript.
– unshift
– shift
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
[Link]
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear TileMill
– id
– idAttribute
– cid Our fellow Knight Foundation News Challenge winners, MapBox, created an open-
– attributes source map design studio with [Link]: TileMill. TileMill lets you manage map
– changed
layers based on shapefiles and rasters, and edit their appearance directly in the
– defaults
– toJSON
browser with the Carto styling language. Note that the gorgeous MapBox homepage is
– sync also a [Link] app.
– fetch
– save
– destroy
– Underscore Methods (9) TileMill
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
– sync
– Underscore Methods (46)
– add
– remove
– reset Blossom
– set
– get
– at Blossom is a lightweight project management tool for lean teams. [Link] is
– push heavily used in combination with CoffeeScript to provide a smooth interaction
– pop
experience. The app is packaged with Brunch. The RESTful backend is built with Flask
– unshift
– shift on Google App Engine.
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
Blossom
[Link] (1.3.3)

» GitHub Repository
» Annotated Source

Getting Started
‑ Introduction
– Models and Views
– Collections
– API Integration
– Rendering
– Routing

Events
– on
– off
– trigger
– once
– listenTo
– stopListening
– listenToOnce
‑ Catalog of Built‑in Events

Model
– extend
Trello
– constructor / initialize
– get
– set Trello is a collaboration tool that organizes your projects into boards. A Trello board
– escape holds many lists of cards, which can contain checklists, files and conversations, and
– has
may be voted on and organized with labels. Updates on the board happen in real time.
– unset
– clear The site was built ground up using [Link] for all the models, views, and routes.
– id
– idAttribute
– cid
– attributes Trello
– changed
– defaults
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (9)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes

Collection
– extend
– model
– modelId
– constructor / initialize
– models
– toJSON
Tzigla
– sync
– Underscore Methods (46) Cristi Balan and Irina Dumitrascu created Tzigla, a collaborative drawing application
– add
where artists make tiles that connect to each other to create surreal drawings.
– remove
– reset Backbone models help organize the code, routers provide bookmarkable deep links,
– set and the views are rendered with [Link] and Zepto. Tzigla is written in Ruby (Rails) on
– get
the backend, and CoffeeScript on the frontend, with Jammit prepackaging the static
– at
– push
assets.
– pop
– unshift
– shift
– slice Tzigla
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync
[Link] (1.3.3)
Change Log
» GitHub Repository
» Annotated Source 1.3.3 — Apr. 5, 2016 — Diff — Docs
Added findIndex and findLastIndex Underscore methods to Collection.
Getting Started
‑ Introduction Added [Link] to Collection "update" event which includes added, merged,
– Models and Views and removed models.
– Collections
– API Integration
Ensured Collection#reduce and Collection#reduceRight work without an initial
– Rendering accumulator value.
– Routing
Ensured Collection#_removeModels always returns an array.

Events Fixed a bug where [Link] with object syntax failed to bind context.
– on
Fixed Collection#_onModelEvent regression where triggering a change event without a
– off
model would error.
– trigger
– once Fixed Collection#set regression when parse returns a falsy value.
– listenTo
– stopListening Fixed Model#id regression where id would be unintentionally undefined.
– listenToOnce
Fixed _removeModels regression which could cause an infinite loop under certain conditions.
‑ Catalog of Built‑in Events
Removed component package support.
Model
Note that 1.3.3 fixes several bugs in versions 1.3.0 to 1.3.2. Please upgrade immediately if you
– extend
are on one of those versions.
– constructor / initialize
– get
– set
– escape
1.2.3 — Sept. 3, 2015 — Diff — Docs
– has Fixed a minor regression in 1.2.2 that would cause an error when adding a model to a
– unset
collection at an out of bounds index.
– clear
– id
– idAttribute
– cid
1.2.2 — Aug. 19, 2015 — Diff — Docs
– attributes Collection methods find, filter, reject, every, some, and partition can now
– changed take a model-attributes-style predicate: [Link]({user: 'guybrush'}).
– defaults
– toJSON Backbone Events once again supports multiple-event maps ( [Link]({'error change':
– sync action})). This was a previously undocumented feature inadvertently removed in 1.2.0.
– fetch
– save
Added Collection#includes as an alias of Collection#contains and as a replacement
– destroy for Collection#include in [Link] >= 1.8.
– Underscore Methods (9)
– validate
– validationError 1.2.1 — Jun. 4, 2015 — Diff — Docs
– isValid
Collection#add now avoids trying to parse a model instance when passed parse:
– url
false.
– urlRoot
– parse Bug fix in Collection#remove. The removed models are now actually returned.
– clone
– isNew Model#fetch no longer parses the response when passing patch: false.
– hasChanged
Bug fix for iframe-based History when used with JSDOM.
– changedAttributes
– previous Bug fix where Collection#invoke was not taking additional arguments.
– previousAttributes
When using on with an event map, you can now pass the context as the second argument.
Collection This was a previously undocumented feature inadvertently removed in 1.2.0.
– extend
– model
– modelId 1.2.0 — May 13, 2015 — Diff — Docs
– constructor / initialize
Added new hooks to Views to allow them to work without jQuery. See the wiki page for more
– models
info.
– toJSON
– sync As a neat side effect, [Link] no longer uses jQuery's event methods for
– Underscore Methods (46) pushState and hashChange listeners. We're native all the way.
– add
– remove Also on the subject of jQuery, if you're using Backbone with CommonJS (node, browserify,
– reset webpack) Backbone will automatically try to load jQuery for you.
– set
– get
Views now always delegate their events in setElement. You can no longer modify the events
– at hash or your view's el property in initialize.
– push
Added an "update" event that triggers after any amount of models are added or removed
– pop
from a collection. Handy to re-render lists of things without debouncing.
– unshift
– shift Collection#at can take a negative index.
– slice
– length Added modelId to Collection for generating unique ids on polymorphic collections. Handy
– comparator for cases when your model ids would otherwise collide.
– sort
Added an overridable _isModel for more advanced control of what's considered a model by
– pluck
your Collection.
– where
– findWhere The success callback passed to Model#destroy is always called asynchronously now.
– url
– parse Router#execute passes back the route name as its third argument.
– clone
Cancel the current Router transition by returning false in Router#execute. Great for
– fetch
checking logged-in status or other prerequisites.
– create
Added getSearch and getPath methods to [Link] as cross-browser and
Router overridable ways of slicing up the URL.
– extend
Added delegate and undelegate as finer-grained versions of delegateEvents and
– routes
undelegateEvents. Useful for plugin authors to use a consistent events interface in
– constructor / initialize
– route
Backbone.
– navigate A collection will only fire a "sort" event if its order was actually updated, not on every set.
– execute
Any passed [Link] are now respected when saving a model with patch: true.
History
Collection#clone now sets the model and comparator functions of the cloned
– start
collection to the new one.

Sync
Adding models to your Collection when specifying an at position now sends the actual
position of your model in the add event, not just the one you've passed in.
[Link] (1.3.3)
Collection#remove will now only return a list of models that have actually been removed
» GitHub Repository
from the collection.
» Annotated Source
Fixed loading [Link] in strict ES6 module loaders.
Getting Started
‑ Introduction
– Models and Views 1.1.2 — Feb. 20, 2014 — Diff — Docs
– Collections
– API Integration Backbone no longer tries to require jQuery in Node/CommonJS environments, for better
– Rendering compatibility with folks using Browserify. If you'd like to have Backbone use jQuery from Node,
– Routing assign it like so: Backbone.$ = require('jquery');

Bugfix for route parameters with newlines in them.


Events
– on
– off
1.1.1 — Feb. 13, 2014 — Diff — Docs
– trigger
– once Backbone now registers itself for AMD ([Link]), Bower and Component, as well as being a
– listenTo CommonJS module and a regular (Java)Script. Whew.
– stopListening
– listenToOnce Added an execute hook to the Router, which allows you to hook in and custom-parse route
‑ Catalog of Built‑in Events arguments, like query strings, for example.

Performance fine-tuning for Backbone Events.


Model
– extend Better matching for Unicode in routes, in old browsers.
– constructor / initialize
Backbone Routers now handle query params in route fragments, passing them into the
– get
handler as the last argument. Routes specified as strings should no longer include the query
– set
string ( 'foo?:query' should be 'foo').
– escape
– has
– unset
– clear 1.1.0 — Oct. 10, 2013 — Diff — Docs
– id
Made the return values of Collection's set, add, remove, and reset more useful. Instead
– idAttribute
of returning this, they now return the changed (added, removed or updated) model or list of
– cid
models.
– attributes
– changed Backbone Views no longer automatically attach options passed to the constructor as
– defaults [Link] and Backbone Models no longer attach url and urlRoot options, but you
– toJSON
can do it yourself if you prefer.
– sync
– fetch All "invalid" events now pass consistent arguments. First the model in question, then the
– save error object, then options.
– destroy
– Underscore Methods (9) You are no longer permitted to change the id of your model during parse. Use
– validate idAttribute instead.
– validationError
On the other hand, parse is now an excellent place to extract and vivify incoming nested
– isValid
JSON into associated submodels.
– url
– urlRoot Many tweaks, optimizations and bugfixes relating to Backbone 1.0, including URL overrides,
– parse mutation of options, bulk ordering, trailing slashes, edge-case listener leaks, nested model
– clone parsing...
– isNew
– hasChanged
– changedAttributes
– previous
1.0.0 — March 20, 2013 — Diff — Docs
– previousAttributes Renamed Collection's "update" to set, for parallelism with the similar [Link](), and
contrast with reset. It's now the default updating mechanism after a fetch. If you'd like to
Collection continue using "reset", pass {reset: true}.
– extend
– model
Your route handlers will now receive their URL parameters pre-decoded.
– modelId Added listenToOnce as the analogue of once.
– constructor / initialize
– models Added the findWhere method to Collections, similar to where.
– toJSON
Added the keys, values, pairs, invert, pick, and omit [Link] methods to
– sync
– Underscore Methods (46)
Backbone Models.
– add The routes in a Router's route map may now be function literals, instead of references to
– remove
methods, if you like.
– reset
– set url and urlRoot properties may now be passed as options when instantiating a new
– get Model.
– at
– push
– pop 0.9.10 — Jan. 15, 2013 — Diff — Docs
– unshift
– shift A "route" event is triggered on the router in addition to being fired on [Link].
– slice
Model validation is now only enforced by default in Model#save and no longer enforced by
– length
– comparator
default upon construction or in Model#set, unless the {validate:true} option is passed.
– sort View#make has been removed. You'll need to use $ directly to construct DOM elements
– pluck
now.
– where
– findWhere Passing {silent:true} on change will no longer delay individual "change:attr" events,
– url instead they are silenced entirely.
– parse
– clone The Model#change method has been removed, as delayed attribute changes are no longer
– fetch available.
– create
Bug fix on change where attribute comparison uses !== instead of _.isEqual.

Router Bug fix where an empty response from the server on save would not call the success function.
– extend
parse now receives options as its second argument.
– routes
– constructor / initialize Model validation now fires invalid event instead of error.
– route
– navigate
– execute 0.9.9 — Dec. 13, 2012 — Diff — Docs
History Added listenTo and stopListening to Events. They can be used as inversion-of-control flavors
– start of on and off, for convenient unbinding of all events an object is currently listening to.
[Link]() automatically calls [Link]().
Sync
When using add on a collection, passing {merge: true} will now cause duplicate models
to have their attributes merged in to the existing models, instead of being ignored.
[Link] (1.3.3)
Added update (which is also available as an option to fetch) for "smart" updating of sets of
» GitHub Repository
models.
» Annotated Source
HTTP PATCH support in save by passing {patch: true}.
Getting Started
The Backbone object now extends Events so that you can use it as a global event bus, if
‑ Introduction
you like.
– Models and Views
– Collections Added a "request" event to [Link], which triggers whenever a request begins to
– API Integration be made to the server. The natural complement to the "sync" event.
– Rendering
– Routing Router URLs now support optional parts via parentheses, without having to use a regex.

Backbone events now supports once, similar to Node's once, or jQuery's one.
Events
– on Backbone events now support jQuery-style event maps [Link]({click: action}).
– off
While listening to a reset event, the list of previous models is now available in
– trigger
[Link], for convenience.
– once
– listenTo Validation now occurs even during "silent" changes. This change means that the isValid
– stopListening method has been removed. Failed validations also trigger an error, even if an error callback is
– listenToOnce
specified in the options.
‑ Catalog of Built‑in Events
Consolidated "sync" and "error" events within [Link]. They are now triggered
Model regardless of the existence of success or error callbacks.
– extend
For mixed-mode APIs, [Link] now accepts emulateHTTP and emulateJSON as
– constructor / initialize
inline options.
– get
– set Collections now also proxy Underscore method name aliases (collect, inject, foldl, foldr, head,
– escape tail, take, and so on...)
– has
– unset Removed getByCid from Collections. [Link] now supports lookup by both id
– clear and cid.
– id
After fetching a model or a collection, all defined parse functions will now be run. So fetching
– idAttribute
a collection and getting back new models could cause both the collection to parse the list, and
– cid
– attributes
then each model to be parsed in turn, if you have both functions defined.
– changed Bugfix for normalizing leading and trailing slashes in the Router definitions. Their presence (or
– defaults
absence) should not affect behavior.
– toJSON
– sync When declaring a View, options, el, tagName, id and className may now be defined
– fetch as functions, if you want their values to be determined at runtime.
– save
– destroy Added a [Link] hook for more convenient overriding of the default use of $.ajax.
– Underscore Methods (9) If AJAX is too passé, set it to your preferred method for server communication.
– validate
Collection#sort now triggers a sort event, instead of a reset event.
– validationError
– isValid Calling destroy on a Model will now return false if the model isNew.
– url
– urlRoot To set what library Backbone uses for DOM manipulation and Ajax calls, use Backbone.$ =
– parse ... instead of setDomLibrary.
– clone
Removed the [Link] helper method. Overriding sync should work better for
– isNew
those particular use cases.
– hasChanged
– changedAttributes To improve the performance of add, [Link] will no longer be set in the add event
– previous callback. [Link](model) can be used to retrieve the index of a model as
– previousAttributes necessary.

Collection For semantic and cross browser reasons, routes will now ignore search parameters. Routes
– extend
like search?query=…&page=3 should become search/…/3.
– model Model#set no longer accepts another model as an argument. This leads to subtle problems
– modelId
and is easily replaced with [Link]([Link]).
– constructor / initialize
– models
– toJSON
– sync
0.9.2 — March 21, 2012 — Diff — Docs
– Underscore Methods (46) Instead of throwing an error when adding duplicate models to a collection, Backbone will now
– add silently skip them instead.
– remove
– reset Added push, pop, unshift, and shift to collections.
– set
A model's changed hash is now exposed for easy reading of the changed attribute delta, since
– get
– at
the model's last "change" event.
– push Added where to collections for simple filtering.
– pop
– unshift You can now use a single off call to remove all callbacks bound to a specific object.
– shift
Bug fixes for nested individual change events, some of which may be "silent".
– slice
– length Bug fixes for URL encoding in [Link] fragments.
– comparator
– sort Bug fix for client-side validation in advance of a save call with {wait: true}.
– pluck
Updated / refreshed the example Todo List app.
– where
– findWhere
– url
– parse 0.9.1 — Feb. 2, 2012 — Diff — Docs
– clone
Reverted to 0.5.3-esque behavior for validating models. Silent changes no longer trigger
– fetch
validation (making it easier to work with forms). Added an isValid function that you can use
– create
to check if a model is currently in a valid state.
Router If you have multiple versions of jQuery on the page, you can now tell Backbone which one to
– extend use with [Link].
– routes
– constructor / initialize
Fixes regressions in 0.9.0 for routing with "root", saving with both "wait" and "validate", and
– route the order of nested "change" events.
– navigate
– execute
0.9.0 — Jan. 30, 2012 — Diff — Docs
History
Creating and destroying models with create and destroy are now optimistic by default.
– start
Pass {wait: true} as an option if you'd like them to wait for a successful server response

Sync
to proceed.

[Link] (1.3.3)
Two new properties on views: $el — a cached jQuery (or Zepto) reference to the view's
element, and setElement, which should be used instead of manually setting a view's el. It
» GitHub Repository
will both set [Link] and view.$el correctly, as well as re-delegating events on the new
» Annotated Source
DOM element.
Getting Started You can now bind and trigger multiple spaced-delimited events at once. For example:
‑ Introduction [Link]("change:name change:age", ...)
– Models and Views
When you don't know the key in advance, you may now call [Link](key, value) as
– Collections
– API Integration
well as save.
– Rendering Multiple models with the same id are no longer allowed in a single collection.
– Routing
Added a "sync" event, which triggers whenever a model's state has been successfully
Events synced with the server (create, save, destroy).
– on
bind and unbind have been renamed to on and off for clarity, following jQuery's lead.
– off
The old names are also still supported.
– trigger
– once A Backbone collection's comparator function may now behave either like a sortBy (pass a
– listenTo function that takes a single argument), or like a sort (pass a comparator function that expects
– stopListening two arguments). The comparator function is also now bound by default to the collection — so
– listenToOnce you can refer to this within it.
‑ Catalog of Built‑in Events
A view's events hash may now also contain direct function values as well as the string
Model names of existing view methods.
– extend Validation has gotten an overhaul — a model's validate function will now be run even for
– constructor / initialize
silent changes, and you can no longer create a model in an initially invalid state.
– get
– set Added shuffle and initial to collections, proxied from Underscore.
– escape
Model#urlRoot may now be defined as a function as well as a value.
– has
– unset View#attributes may now be defined as a function as well as a value.
– clear
– id Calling fetch on a collection will now cause all fetched JSON to be run through the
– idAttribute collection's model's parse function, if one is defined.
– cid
– attributes
You may now tell a router to navigate(fragment, {replace: true}), which will either use
– changed [Link] or [Link], in order to change the URL without
– defaults adding a history entry.
– toJSON
Within a collection's add and remove events, the index of the model being added or
– sync
removed is now available as [Link].
– fetch
– save Added an undelegateEvents to views, allowing you to manually remove all configured event
– destroy delegations.
– Underscore Methods (9)
– validate Although you shouldn't be writing your routes with them in any case — leading slashes ( /)
– validationError are now stripped from routes.
– isValid
Calling clone on a model now only passes the attributes for duplication, not a reference to
– url
the model itself.
– urlRoot
– parse Calling clear on a model now removes the id attribute.
– clone
– isNew
– hasChanged
0.5.3 — August 9, 2011 — Diff — Docs
– changedAttributes
– previous A View's events property may now be defined as a function, as well as an object
– previousAttributes literal, making it easier to programmatically define and inherit events. groupBy is now
proxied from Underscore as a method on Collections. If the server has already rendered
Collection
everything on page load, pass [Link]({silent: true}) to prevent
– extend
– model the initial route from triggering. Bugfix for pushState with encoded URLs.
– modelId
– constructor / initialize
– models 0.5.2 — July 26, 2011 — Diff — Docs
– toJSON
– sync The bind function, can now take an optional third argument, to specify the this of
– Underscore Methods (46) the callback function. Multiple models with the same id are now allowed in a
– add collection. Fixed a bug where calling .fetch(jQueryOptions) could cause an incorrect
– remove
URL to be serialized. Fixed a brief extra route fire before redirect, when degrading from
– reset
– set pushState.
– get
– at
– push 0.5.1 — July 5, 2011 — Diff — Docs
– pop
– unshift Cleanups from the 0.5.0 release, to wit: improved transparent upgrades from hash-
– shift based URLs to pushState, and vice-versa. Fixed inconsistency with non-modified
– slice attributes being passed to Model#initialize. Reverted a 0.5.0 change that would
– length
strip leading hashbangs from routes. Added contains as an alias for includes.
– comparator
– sort
– pluck
– where 0.5.0 — July 1, 2011 — Diff — Docs
– findWhere
A large number of tiny tweaks and micro bugfixes, best viewed by looking at the
– url
– parse commit diff. HTML5 pushState support, enabled by opting-in with:
– clone [Link]({pushState: true}). Controller was renamed to
– fetch Router, for clarity. Collection#refresh was renamed to Collection#reset to
– create
emphasize its ability to both reset the collection with new models, as well as empty out
Router the collection when used with no parameters. saveLocation was replaced with
– extend navigate. RESTful persistence methods (save, fetch, etc.) now return the jQuery
– routes deferred object for further success/error chaining and general convenience. Improved
– constructor / initialize
XSS escaping for Model#escape. Added a urlRoot option to allow specifying RESTful
– route
– navigate urls without the use of a collection. An error is thrown if [Link] is
– execute called multiple times. Collection#create now validates before initializing the new
model. [Link] can now be a jQuery string lookup. Backbone Views can now also
History
take an attributes parameter. Model#defaults can now be a function as well as a
– start
literal attributes object.
Sync
0.3.3 — Dec 1, 2010 — Diff — Docs
[Link] (1.3.3) [Link] now supports Zepto, alongside jQuery, as a framework for DOM
» GitHub Repository manipulation and Ajax support. Implemented Model#escape, to efficiently handle
» Annotated Source
attributes intended for HTML interpolation. When trying to persist a model, failed
Getting Started requests will now trigger an "error" event. The ubiquitous options argument is now
‑ Introduction passed as the final argument to all "change" events.
– Models and Views
– Collections
– API Integration 0.3.2 — Nov 23, 2010 — Diff — Docs
– Rendering
– Routing
Bugfix for IE7 + iframe-based "hashchange" events. sync may now be overridden on a
per-model, or per-collection basis. Fixed recursion error when calling save with no
Events changed attributes, within a "change" event.
– on
– off
– trigger 0.3.1 — Nov 15, 2010 — Diff — Docs
– once
– listenTo All "add" and "remove" events are now sent through the model, so that views can
– stopListening listen for them without having to know about the collection. Added a remove method to
– listenToOnce
[Link]. toJSON is no longer called at all for 'read' and 'delete' requests.
‑ Catalog of Built‑in Events
Backbone routes are now able to load empty URL fragments.
Model
– extend
– constructor / initialize
0.3.0 — Nov 9, 2010 — Diff — Docs
– get Backbone now has Controllers and History, for doing client-side routing based on URL
– set
fragments. Added emulateHTTP to provide support for legacy servers that don't do
– escape
– has PUT and DELETE. Added emulateJSON for servers that can't accept
– unset application/json encoded requests. Added Model#clear, which removes all
– clear
attributes from a model. All Backbone classes may now be seamlessly inherited by
– id
– idAttribute
CoffeeScript classes.
– cid
– attributes
– changed 0.2.0 — Oct 25, 2010 — Diff — Docs
– defaults
Instead of requiring server responses to be namespaced under a model key, now you
– toJSON
– sync can define your own parse method to convert responses into attributes for Models and
– fetch Collections. The old handleEvents function is now named delegateEvents, and is
– save
automatically called as part of the View's constructor. Added a toJSON function to
– destroy
– Underscore Methods (9)
Collections. Added Underscore's chain to Collections.
– validate
– validationError
– isValid 0.1.2 — Oct 19, 2010 — Diff — Docs
– url
Added a Model#fetch method for refreshing the attributes of single model from the
– urlRoot
– parse server. An error callback may now be passed to set and save as an option, which
– clone will be invoked if validation fails, overriding the "error" event. You can now tell
– isNew
backbone to use the _method hack instead of HTTP methods by setting
– hasChanged
[Link] = true. Existing Model and Collection data is no longer sent
– changedAttributes
– previous up unnecessarily with GET and DELETE requests. Added a rake lint task. Backbone
– previousAttributes is now published as an NPM module.

Collection
– extend 0.1.1 — Oct 14, 2010 — Diff — Docs
– model
– modelId Added a convention for initialize functions to be called upon instance construction,
– constructor / initialize if defined. Documentation tweaks.
– models
– toJSON
– sync 0.1.0 — Oct 13, 2010 — Docs
– Underscore Methods (46)
– add Initial Backbone release.
– remove
– reset
– set
– get
– at
– push
– pop
– unshift
– shift
– slice
– length
– comparator
– sort
– pluck
– where
– findWhere
– url
– parse
– clone
– fetch
– create

Router
– extend
– routes
– constructor / initialize
– route
– navigate
– execute

History
– start

Sync

You might also like