Introduction

bolivialodgeInternet και Εφαρμογές Web

14 Δεκ 2013 (πριν από 3 χρόνια και 8 μήνες)

205 εμφανίσεις

2/5/13
Backbone.js
backbonejs.org
1/60
Backbone.js gives structure to web applications
by providing
models
with key-value
binding and custom events,
collections
with a rich API of enumerable functions,
views
with declarative event handling, and connects it all to your
existing API over a
RESTful JSON interface.
The project is
hosted on GitHub
,
and the
annotated source code
is available,
as well as
an online
test suite
,
an
example application
,
a
list of tutorials

and a
long list of real-
world projects
that use Backbone.
Backbone is available for use under the
MIT
software license
.
You can report bugs and discuss features on the
GitHub issues page
,
on Freenode
IRC in the
#documentcloud
channel, post questions to the
Google Group
,
add pages
to the
wiki

or send tweets to
@documentcloud
.
Backbone is an open-source component of
DocumentCloud
.
Downloads & Dependencies
(Right-click, and use "Save As")
Development Version (0.9.10)
Development Version (0.9.10)
56kb, Full source, lots of comments
Production Version (0.9.10)
Production Version (0.9.10)
6.3kb, Packed and gzipped
Edge Version (master)
Edge Version (master)
Unreleased, use at your own risk
Backbone's only hard dependency is either
Underscore.js

( >= 1.4.3)
or
Lo-Dash
.
For
RESTful persistence, history support via
Backbone.Router

and DOM manipulation with
Backbone.View
, include
json2.js
, and either
jQuery

( >= 1.7.0)
or
Zepto
.
Introduction
When working on a web application that involves a lot of JavaScript, one
of the first
things you learn is to stop tying your data to the DOM. It's all
too easy to create
JavaScript applications that end up as tangled piles of
jQuery selectors and callbacks,
all trying frantically to keep data in
sync between the HTML UI, your JavaScript logic,
and the database on your
server. For rich client-side applications, a more structured
approach
is often helpful.
With Backbone, you represent your data as
Models
, which can be created, validated,
destroyed,
and saved to the server. Whenever a UI action causes an attribute of
a
model to change, the model triggers a
"change"
event; all
the
Views
that display the
model's state can be notified of the
change, so that they are able to respond
accordingly, re-rendering themselves with
the new information. In a finished Backbone
Backbone.js
(0.9.10)
»
GitHub Repository
»
Annotated Source
Introduction
Upgrading
Events

on

off

trigger

once

listenTo

stopListening
-
Catalog of Built-in Events
Model

extend

constructor / initialize

get

set

escape

has

unset

clear

id

idAttribute

cid

attributes

changed

defaults

toJSON

sync

fetch

save

destroy

validate

validationError

url

urlRoot

parse

clone

isNew

hasChanged

changedAttributes

previous

previousAttributes
Collection

extend

model

constructor / initialize

models
2/5/13
Backbone.js
backbonejs.org
2/60
app, you don't have to write the glue
code that looks into the DOM to find an element
with a specific
id
,
and update the HTML manually
— when the model changes, the
views simply update themselves.
If you're new here, and aren't yet quite sure what Backbone is for, start by
browsing the
list of Backbone-based projects
.
Many of the examples that follow are runnable. Click the
play
button
to execute them.
Upgrading to 0.9.10
Backbone
0.9.10
should be considered as a release candidate
for an upcoming
1.0
. If
you're upgrading from a previous version,
be sure to check the
change log
. In brief, a
few of the larger changes
are:
Most importantly, Backbone events have two new methods:
listenTo
and
stopListening
. These
are an
inversion-of-control flavor of the usual
on
and
off
,
and make it a little easier to clean
up
all
events
that an object is listening to on other objects. When you destroy Views
with
view.remove()
, this will now be done
automatically. Note that the usual rules about
programming in a garbage
collected language still apply.
HTTP
PATCH
support, via
model.save(attrs, {patch: true})
,
if you'd like to send only
partial updates to the server.
An
update
method was added to Collection,
which should make it easier to perform "smart"
syncing updates with the
server, where models are added or removed, and updated attributes
are merged
as appropriate. If you were previously using
collection.fetch({add: true})
,
try
update
instead.
Backbone events now support
once
.
Model validation is now only enforced by default in
Model#save
and no longer enforced by
default upon
construction or in
Model#set
, unless the
{validate:true}

option is passed.
Passing
{silent:true}
on change will no longer delay individual
"change:attr"
events,
instead they are silenced entirely.
The
Model#change
method has been removed, as delayed attribute
changes are no longer
available.
Backbone.Events
Events
is a module that can be mixed in to any object, giving the
object the ability to
bind and trigger custom named events. Events do not
have to be declared before they
are bound, and may take passed arguments.
For example:
var object = {};
_.extend(object, Backbone.Events);
object.on("alert", function(msg) {
alert("Triggered " + msg);
});
object.trigger("alert", "an event");
For example, to make a handy event dispatcher that can coordinate events
among
different areas of your application:
var dispatcher = _.clone(Backbone.Events)
2/5/13
Backbone.js
backbonejs.org
3/60
on
object.on(event, callback, [context])
Alias: bind

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
use colons to
namespace them:
"poll:start"
, or
"change:selection"
.
The event
string may also be a space-delimited list of several events...
book.on("change:title change:author", ...);
To supply a
context
value for
this
when the callback is invoked,
pass the optional
third argument:
model.on('change', this.render, this)
Callbacks bound to the special
"all"
event will be triggered when any event occurs,
and are passed
the name of the event as the first argument. For example, to proxy all
events
from one object to another:
proxy.on("all", function(eventName) {
object.trigger(eventName);
});
All Backbone event methods also support an event map syntax, as an alternative
to
positional arguments:
book.on({
"change:title": titleView.update,
"change:author": authorPane.update,
"destroy": bookView.remove
});
off
object.off([event], [callback], [context])
Alias: unbind

Remove a previously-bound
callback
function from an object. If no
context
is
specified, all of the versions of the callback with
different contexts will be removed. If no
callback is specified, all callbacks for the
event
will be
removed. If no event is
specified, callbacks for
all
events
will be removed.
// Removes just the `onChange` callback.
object.off("change", onChange);
// Removes all "change" callbacks.
object.off("change");
// Removes the `onChange` callback for all events.
object.off(null, onChange);
// Removes all callbacks for `context` for all events.
object.off(null, null, context);
// Removes all callbacks on `object`.
object.off();
Note that calling
model.off()
, for example, will indeed remove
all
events
on the model
— including events that Backbone uses for internal bookkeeping.
trigger
object.trigger(event, [*args])

Trigger callbacks for the given
event
, or space-delimited list of events.
Subsequent
arguments to
trigger
will be passed along to the
event callbacks.
2/5/13
Backbone.js
backbonejs.org
4/60
once
object.once(event, callback, [context])

Just like
on
, but causes the bound callback to only
fire once before being removed.
Handy for saying "the next time that X happens, do this".
listenTo
object.listenTo(other, event, callback)

Tell an
object
to listen to a particular event on an
other
object.
The advantage of
using this form, instead of
other.on(event, callback)
,
is that
listenTo
allows the
object
to keep track of the events,
and they can be removed all at once later on.
view.listenTo(model, 'change', view.render);
stopListening
object.stopListening([other], [event], [callback])

Tell an
object
to stop listening to events. Either call
stopListening
with no arguments
to have the
object
remove
all of its
registered
callbacks ... or be more
precise by
telling it to remove just the events it's listening to on a
specific object, or a specific
event, or just a specific callback.
view.stopListening();
view.stopListening(model);
Catalog of Events

Here's the complete list of built-in Backbone events, with arguments.
You're also free to
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 application needs.
"add"
(model, collection, options) — when a model is added to a collection.
"remove"
(model, collection, options) — when a model is removed from a collection.
"reset"
(collection, options) — when the collection's entire contents have been replaced.
"sort"
(collection, options) — when the collection has been re-sorted.
"change"
(model, options) — when a model's attributes have changed.
"change:[attribute]"
(model, value, options) — when a specific attribute has been updated.
"destroy"
(model, collection, options) — when a model is
destroyed
.
"request"
(model, xhr, options) — when a model (or collection) has started a request to the server.
"sync"
(model, resp, options) — when a model (or collection) has been successfully synced with the
server.
"error"
(model, xhr, options) — when a model's
save
call fails on the server.
"invalid"
(model, error, options) — when a model's
validation
fails on the client.
"route:[name]"
(params) — Fired by the router when a specific route is matched.
"route"
(router, route, params) — Fired by history (or router) when
any
route has been matched.
"all"
— this special event fires for
any
triggered event, passing the event name as the first argument.
Backbone.Model
Models
are the heart of any JavaScript application, containing
the interactive data as
well as a large part of the logic surrounding it:
conversions, validations, computed
2/5/13
Backbone.js
backbonejs.org
5/60
properties, and access control. You
extend
Backbone.Model
with your domain-
specific methods, and
Model
provides a basic set of functionality for managing
changes.
The following is a contrived example, but it demonstrates defining a model
with a
custom method, setting an attribute, and firing an event keyed
to changes in that
specific attribute.
After running this code once,
sidebar
will be
available in your
browser's console, so you can play around with it.
var Sidebar = Backbone.Model.extend({
promptColor: function() {
var cssColor = prompt("Please enter a CSS color:");
this.set({color: cssColor});
}
});
window.sidebar = new Sidebar;
sidebar.on('change:color', function(model, color) {
$('#sidebar').css({background: color});
});
sidebar.set({color: 'white'});
sidebar.promptColor();
extend
Backbone.Model.extend(properties, [classProperties])

To create a
Model
class of your own, you extend
Backbone.Model

and provide
instance
properties
, as well as optional
classProperties
to be attached directly to
the constructor function.
extend
correctly sets up the prototype chain, so subclasses created
with
extend
can
be further extended and subclassed as far as you like.
var Note = Backbone.Model.extend({
initialize: function() { ... },
author: function() { ... },
coordinates: function() { ... },
allowedToEdit: function(account) {
return true;
}
});
var PrivateNote = Note.extend({
allowedToEdit: function(account) {
return account.owns(this);
}
});
Brief aside on
super
: JavaScript does not provide
a simple way to call super — the function of the
same name defined
higher on the prototype chain. If you override a core function like
set
, or
save
, and you want to invoke the
parent object's implementation, you'll have to explicitly call it,
along these lines:
2/5/13
Backbone.js
backbonejs.org
6/60
var Note = Backbone.Model.extend({
set: function(attributes, options) {
Backbone.Model.prototype.set.apply(this, arguments);
...
}
});
constructor / initialize
new Model([attributes], [options])

When creating an instance of a model, you can pass in the initial values
of the
attributes
, which will be
set
on the
model. If you define an
initialize
function, it will be
invoked when
the model is created.
new Book({
title: "One Thousand and One Nights",
author: "Scheherazade"
});
In rare cases, if you're looking to get fancy,
you may want to override
constructor
,
which allows
you to replace the actual constructor function for your model.
If you pass a
{collection: ...}
as the
options
, the model
gains a
collection
property that will be used to indicate which
collection the model belongs to, and is used
to help compute the model's
url
. The
model.collection
property is
otherwise added
automatically when you first add a model to a collection.
get
model.get(attribute)

Get the current value of an attribute from the model. For example:
note.get("title")
set
model.set(attributes, [options])

Set a hash of attributes (one or many) on the model. If any of the attributes
change the
model's state, a
"change"
event will be triggered, unless
{silent: true}
is passed
as an option. Change events for specific
attributes are also triggered, and you can bind
to those as well, for example:
change:title
, and
change:content
. You may also pass
individual keys and values.
note.set({title: "March 20", content: "In his eyes she eclipses..."});
book.set("title", "A Scandal in Bohemia");
escape
model.escape(attribute)

Similar to
get
, but returns the HTML-escaped version
of a model's attribute. If you're
interpolating data from the model into
HTML, using
escape
to retrieve attributes will
prevent
XSS
attacks.
var hacker = new Backbone.Model({
name: "<script>alert('xss')</script>"
});
alert(hacker.escape('name'));
has
model.has(attribute)

Returns
true
if the attribute is set to a non-null or non-undefined
value.
2/5/13
Backbone.js
backbonejs.org
7/60
if (note.has("title")) {
...
}
unset
model.unset(attribute, [options])

Remove an attribute by deleting it from the internal attributes hash.
Fires a
"change"
event unless
silent
is passed as an option.
clear
model.clear([options])

Removes all attributes from the model, including the
id
attribute. Fires a
"change"
event unless
silent
is passed as an option.
id
model.id

A special property of models, the
id
is an arbitrary string
(integer id or UUID). If you set
the
id
in the
attributes hash, it will be copied onto the model as a direct property.
Models can be retrieved by id from collections, and the id is used to generate
model
URLs by default.
idAttribute
model.idAttribute

A model's unique identifier is stored under the
id
attribute.
If you're directly
communicating with a backend (CouchDB, MongoDB) that uses
a different unique key,
you may set a Model's
idAttribute
to
transparently map from that key to
id
.
var Meal = Backbone.Model.extend({
idAttribute: "_id"
});
var cake = new Meal({ _id: 1, name: "Cake" });
alert("Cake id: " + cake.id);
cid
model.cid

A special property of models, the
cid
or client id is a unique identifier
automatically
assigned to all models when they're first created. Client ids
are handy when the model
has not yet been saved to the server, and does not
yet have its eventual true
id
, but
already needs to be visible in the UI.
attributes
model.attributes

The
attributes
property is the internal hash containing the model's
state — usually
(but not necessarily) a form of the JSON object
representing the model data on the
server. It's often a straightforward
serialization of a row from the database, but it could
also be client-side
computed state.
Please use
set
to update the
attributes

instead of modifying them directly. If you'd like
to retrieve and munge a
copy of the model's attributes, use
_.clone(model.attributes)

instead.
Due to the fact that
Events
accepts space separated
lists of events, attribute names should not
include spaces.
changed
model.changed

The
changed
property is the internal hash containing all the attributes
that have
2/5/13
Backbone.js
backbonejs.org
8/60
changed since the last
"change"
event was triggered.
Please do not update
changed
directly since its state is internally maintained
by
set
.
A copy of
changed
can be
acquired from
changedAttributes
.
defaults
model.defaults or model.defaults()

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
their default value.
var Meal = Backbone.Model.extend({
defaults: {
"appetizer": "caesar salad",
"entree": "ravioli",
"dessert": "cheesecake"
}
});
alert("Dessert will be " + (new Meal).get('dessert'));
Remember that in JavaScript, objects are passed by reference, so if you
include an object as a
default value, it will be shared among all instances.
Instead, define
defaults
as a function.
toJSON
model.toJSON()

Return a copy of the model's
attributes

for JSON stringification.
This can be used for
persistence,
serialization, or for augmentation before being sent to the server. The
name of this method is a bit confusing, as it doesn't actually return a
JSON string — but
I'm afraid that it's the way that the
JavaScript API for
JSON.stringify

works.
var artist = new Backbone.Model({
firstName: "Wassily",
lastName: "Kandinsky"
});
artist.set({birthday: "December 16, 1866"});
alert(JSON.stringify(artist));
sync
model.sync(method, model, [options])

Uses
Backbone.sync
to persist the state of a model to
the server.
Can be overridden
for custom behavior.
fetch
model.fetch([options])

Resets the model's state from the server by delegating to
Backbone.sync
. Returns a
jqXHR
.
Useful if the model has never
been populated with data, or if you'd like to
ensure that you have the
latest server state. A
"change"
event will be triggered if the
server's state differs from the current attributes. Accepts
success
and
error
callbacks in the options hash, which
are passed
(model, response, options)

and
(model, xhr, options)
as arguments, respectively.
// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
channel.fetch();
}, 10000);
2/5/13
Backbone.js
backbonejs.org
9/60
save
model.save([attributes], [options])

Save a model to your database (or alternative persistence layer),
by delegating to
Backbone.sync
.
Returns a
jqXHR
if
validation is successful and
false
otherwise. The
attributes

hash (as in
set
) should contain the attributes
you'd like to change — keys
that aren't mentioned won't be altered — but,
a
complete representation
of the
resource will be sent to the server.
As with
set
, you may pass individual keys and
values instead of a hash.
If the model has a
validate

method, and validation fails, the
model will not be saved. If the model
isNew
, the save will be a
"create"

(HTTP
POST
),
if the model already
exists on the server, the save will be an
"update"
(HTTP
PUT
).
If instead, you'd only like the
changed
attributes to be sent to the
server, call
model.save(attrs, {patch: true})
. You'll get an HTTP
PATCH
request to the server
with just the passed-in attributes.
Calling
save
with new attributes will cause a
"change"

event immediately, a
"request"
event as the Ajax request begins to
go to the server, and a
"sync"
event
after the server has acknowledged
the successful change. Pass
{wait: true}
if you'd
like to wait
for the server before setting the new attributes on the model.
In the following example, notice how our overridden version
of
Backbone.sync
receives
a
"create"
request
the first time the model is saved and an
"update"

request the
second time.
Backbone.sync = function(method, model) {
alert(method + ": " + JSON.stringify(model));
model.id = 1;
};
var book = new Backbone.Model({
title: "The Rough Riders",
author: "Theodore Roosevelt"
});
book.save();
book.save({author: "Teddy"});
save
accepts
success
and
error
callbacks in the
options hash, which are passed
(model, response, options)
and
(model, xhr, options)
as arguments,
respectively.
If a server-side validation fails, return a non-
200

HTTP response code,
along with an error response in text or JSON.
book.save("author", "F.D.R.", {error: function(){ ... }});
destroy
model.destroy([options])

Destroys the model on the server by delegating an HTTP
DELETE

request to
Backbone.sync
. Returns a
jqXHR
object, or
false
if the model
isNew
. Accepts
success
and
error
callbacks in the options hash, which
are passed
(model,
response, options)
and
(model, xhr, options)

as arguments, respectively.
Triggers a
"destroy"
event on the model, which will bubble up
through any collections
that contain it, a
"request"
event as it
begins the Ajax request to the server, and a
"sync"
event, after
the server has successfully acknowledged the model's deletion.
Pass
{wait: true}
if you'd like to wait for the server to respond
before removing the
model from the collection.
2/5/13
Backbone.js
backbonejs.org
10/60
book.destroy({success: function(model, response) {
...
}});
validate
model.validate(attributes, options)

This method is left undefined, and you're encouraged to override it with
your custom
validation logic, if you have any that can be performed
in JavaScript. By default
validate
is called before
save
, but can also be called before
set
if
{validate:true}
is passed. The
validate
method is passed
the model attributes, as well as the options
from
set
or
save
.
If the attributes are valid, don't return anything from
validate
;
if
they are invalid, return an error of your choosing. It
can be as simple as a string error
message to be displayed, or a complete
error object that describes the error
programmatically. If
validate

returns an error,
set
and
save
will not continue, and
the
model attributes will not be modified.
Failed validations trigger an
"invalid"
event,
and set the
validationError
property on the model with the value returned by
this
method.
var Chapter = Backbone.Model.extend({
validate: function(attrs, options) {
if (attrs.end < attrs.start) {
return "can't end before it starts";
}
}
});
var one = new Chapter({
title : "Chapter One: The Beginning"
});
one.on("invalid", function(model, error) {
alert(model.get("title") + " " + error);
});
one.save({
start: 15,
end: 10
});
"invalid"
events are useful for providing coarse-grained error
messages at the
model or collection level.
validationError
model.validationError

The value returned by
validate
during the last failed validation.
url
model.url()

Returns the relative URL where the model's resource would be located on
the server. If
your models are located somewhere else, override this method
with the correct logic.
Generates URLs of the form:
"[collection.url]/[id]"

by default, but you may
override by specifying an explicit
urlRoot

if the model's collection shouldn't be taken
into account.
Delegates to
Collection#url
to generate the
URL, so make sure that you have it
defined, or a
urlRoot

property, if all models of this class share a common root URL.
A
model with an id of
101
, stored in a
Backbone.Collection
with a
url
of
"/documents/7/notes"
,
would have this URL:
"/documents/7/notes/101"
2/5/13
Backbone.js
backbonejs.org
11/60
urlRoot
model.urlRoot or model.urlRoot()

Specify a
urlRoot
if you're using a model
outside
of a collection,
to enable the default
url
function to generate
URLs based on the model id.
"[urlRoot]/id"
Normally, you won't need to define this.
Note that
urlRoot
may also be a function.
var Book = Backbone.Model.extend({urlRoot : '/books'});
var solaris = new Book({id: "1083-lem-solaris"});
alert(solaris.url());
parse
model.parse(response)

parse
is called whenever a model's data is returned by the
server, in
fetch
, and
save
.
The function is passed the raw
response
object, and should return
the attributes hash
to be
set
on the model. The
default implementation is a no-op, simply passing through
the JSON response.
Override this if you need to work with a preexisting API, or better
namespace
your responses.
If you're working with a Rails backend that has a version prior to 3.1,
you'll notice that
its default
to_json
implementation includes
a model's attributes under a namespace.
To disable this behavior for
seamless Backbone integration, set:
ActiveRecord::Base.include_root_in_json = false
clone
model.clone()

Returns a new instance of the model with identical attributes.
isNew
model.isNew()

Has this model been saved to the server yet? If the model does not yet have
an
id
, it
is considered to be new.
hasChanged
model.hasChanged([attribute])

Has the model changed since the last
"change"
event? If an
attribute

is passed,
returns
true
if that specific attribute has changed.
Note that this method, and the following change-related ones,
are only useful during the course of a
"change"
event.
book.on("change", function() {
if (book.hasChanged("title")) {
...
}
});
changedAttributes
model.changedAttributes([attributes])

Retrieve a hash of only the model's attributes that have changed. Optionally,
an
external
attributes
hash can be passed in, returning
the attributes in that hash which
differ from the model. This can be used
to figure out which portions of a view should be
updated, or what calls
need to be made to sync the changes to the server.
previous
model.previous(attribute)

2/5/13
Backbone.js
backbonejs.org
12/60
During a
"change"
event, this method can be used to get the
previous value of a
changed attribute.
var bill = new Backbone.Model({
name: "Bill Smith"
});
bill.on("change:name", function(model, name) {
alert("Changed name from " + bill.previous("name") + " to " + name);
});
bill.set({name : "Bill Jones"});
previousAttributes
model.previousAttributes()

Return a copy of the model's previous attributes. Useful for getting a
diff between
versions of a model, or getting back to a valid state after
an error occurs.
Backbone.Collection
Collections are ordered sets of models. You can bind
"change"
events
to be notified
when any model in the collection has been modified,
listen for
"add"
and
"remove"
events,
fetch

the collection from the server, and use a full suite of
Underscore.js
methods
.
Any event that is triggered on a model in a collection will also be
triggered on the
collection directly, for convenience.
This allows you to listen for changes to specific
attributes in any
model in a collection, for example:
Documents.on("change:selected",
...)
extend
Backbone.Collection.extend(properties, [classProperties])

To create a
Collection
class of your own, extend
Backbone.Collection
,
providing
instance
properties
, as well as optional
classProperties
to be attached
directly to
the collection's constructor function.
model
collection.model

Override this property to specify the model class that the collection
contains. If defined,
you can pass raw attributes objects (and arrays) to
add
,
create
,
and
reset
, and the
attributes will be
converted into a model of the proper type.
var Library = Backbone.Collection.extend({
model: Book
});
constructor / initialize
new Collection([models], [options])

When creating a Collection, you may choose to pass in the initial array
of
models
.
The
collection's
comparator

may be included as an option. Passing
false
as the
comparator option will prevent sorting. If you define an
initialize
function, it will be
invoked when the collection is
created.
var tabs = new TabSet([tab1, tab2, tab3]);
2/5/13
Backbone.js
backbonejs.org
13/60
models
collection.models

Raw access to the JavaScript array of models inside of the collection. Usually you'll
want to use
get
,
at
, or the
Underscore methods

to access model objects, but
occasionally a direct reference to the array
is desired.
toJSON
collection.toJSON()

Return an array containing the attributes hash of each model in the
collection. This can
be used to serialize and persist the
collection as a whole. The name of this method is a
bit confusing, because
it conforms to
JavaScript's JSON API
.
var collection = new Backbone.Collection([
{name: "Tim", age: 5},
{name: "Ida", age: 26},
{name: "Rob", age: 55}
]);
alert(JSON.stringify(collection));
sync
collection.sync(method, collection, [options])

Uses
Backbone.sync
to persist the state of a
collection to the server.
Can be
overridden for custom behavior.
Underscore Methods (28)

Backbone proxies to
Underscore.js
to provide 28 iteration functions
on
Backbone.Collection
. They aren't all documented here, but
you can take a look at
the Underscore documentation for the full details…
forEach (each)
map (collect)
reduce (foldl, inject)
reduceRight (foldr)
find (detect)
filter (select)
reject
every (all)
some (any)
include (contains)
invoke
max
min
sortBy
groupBy
sortedIndex
shuffle
toArray
size
first (head, take)
2/5/13
Backbone.js
backbonejs.org
14/60
initial
rest (tail)
last
without
indexOf
lastIndexOf
isEmpty
chain
Books.each(function(book) {
book.publish();
});
var titles = Books.map(function(book) {
return book.get("title");
});
var publishedBooks = Books.filter(function(book) {
return book.get("published") === true;
});
var alphabetical = Books.sortBy(function(book) {
return book.author.get("name").toLowerCase();
});
add
collection.add(models, [options])

Add a model (or an array of models) to the collection. Fires an
"add"

event, which you
can pass
{silent: true}
to suppress. If a
model
property is defined, you may also
pass
raw attributes objects, and have them be vivified as instances of the model.
Pass
{at: index}
to splice the model into the collection at the
specified
index
. If you're
adding models to the collection that are
already
in the collection, they'll be ignored,
unless you pass
{merge: true}
, in which case their attributes will be merged
into the
corresponding models, firing any appropriate
"change"
events.
var ships = new Backbone.Collection;
ships.on("add", function(ship) {
alert("Ahoy " + ship.get("name") + "!");
});
ships.add([
{name: "Flying Dutchman"},
{name: "Black Pearl"}
]);
Note that adding the same model (a model with the same
id
) to
a collection more than once
is a no-op.
remove
collection.remove(models, [options])

Remove a model (or an array of models) from the collection. Fires a
"remove"
event,
which you can use
silent

to suppress. If you're a callback listening to the
"remove"
event,
the index at which the model is being removed from the collection is available
as
options.index
.
reset
collection.reset([models], [options])

2/5/13
Backbone.js
backbonejs.org
15/60
Adding and removing models one at a time is all well and good, but sometimes
you
have so many models to change that you'd rather just update the collection
in bulk. Use
reset
to replace a collection with a new list
of models (or attribute hashes), triggering a
single
"reset"
event
at the end. Pass
{silent: true}
to suppress the
"reset"
event.
For convenience, within a
"reset"
event, the list of any previous
models is
available as
options.previousModels
.
Here's an example using
reset
to bootstrap a collection during initial page load,
in a
Rails application:
<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= @accounts.to_json %>);
</script>
Calling
collection.reset()
without passing any models as arguments
will empty the
entire collection.
update
collection.update(models, [options])

The
update
method tries to peform a "smart" update of the collection
with the passed
list of models. If a model in the list isn't yet in the
collection it will be added; if the model
is already in the collection
its attributes will be merged; and if the collection contains
any 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. If you'd like to
customize the behavior, you can disable
it with options:
{add: false}
,
{remove:
false}
, or
{merge: false}
.
var vanHalen = new Collection([eddie, alex, stone, roth]);
vanHalen.update([eddie, alex, stone, hagar]);
// Fires a "remove" event for roth, and an "add" event for "hagar".
// Updates any of stone, alex, and eddie's attributes that may have
// changed over the years.
get
collection.get(id)

Get a model from a collection, specified by an
id
,
a
cid
, or by passing in a
model
.
var book = Library.get(110);
at
collection.at(index)

Get a model from a collection, specified by index. Useful if your collection
is sorted, and
if your collection isn't sorted,
at
will still
retrieve models in insertion order.
push
collection.push(model, [options])

Add a model at the end of a collection. Takes the same options as
add
.
pop
collection.pop([options])

Remove and return the last model from a collection. Takes the same options as
remove
.
2/5/13
Backbone.js
backbonejs.org
16/60
unshift
collection.unshift(model, [options])

Add a model at the beginning of a collection. Takes the same options as
add
.
shift
collection.shift([options])

Remove and return the first model from a collection. Takes the same options as
remove
.
length
collection.length

Like an array, a Collection maintains a
length
property, counting
the number of
models it contains.
comparator
collection.comparator

By default there is no
comparator
for a collection.
If you define a comparator, it will be
used to maintain
the collection in sorted order. This means that as models are added,
they are inserted at the correct index in
collection.models
.
A comparator can be
defined as a
sortBy

(pass a function that takes a single argument),
as a
sort

(pass a
comparator function that expects two arguments),
or as a string indicating the attribute
to sort by.
"sortBy" comparator functions take a model and return a numeric or string
value by
which the model should be ordered relative to others.
"sort" comparator functions take
two models, and return
-1
if
the first model should come before the second,
0
if they
are of
the same rank and
1
if the first model should come after.
Note how even though all of the chapters in this example are added backwards,
they
come out in the proper order:
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = function(chapter) {
return chapter.get("page");
};
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
alert(chapters.pluck('title'));
Collections with a comparator will not automatically re-sort if you
later change model attributes, so
you may wish to call
sort
after changing model attributes that would affect the order.
sort
collection.sort([options])

Force a collection to re-sort itself. You don't need to call this under
normal
circumstances, as a collection with a
comparator

will sort itself whenever a model is
added. To disable sorting when adding
a model, pass
{sort: false}
to
add
. Calling
sort

triggers a
"sort"
event on the collection, unless silenced by
passing
{silent:
true}
.
pluck
collection.pluck(attribute)

Pluck an attribute from each model in the collection. Equivalent to calling
map
, and
2/5/13
Backbone.js
backbonejs.org
17/60
returning a single attribute from the iterator.
var stooges = new Backbone.Collection([
{name: "Curly"},
{name: "Larry"},
{name: "Moe"}
]);
var names = stooges.pluck("name");
alert(JSON.stringify(names));
where
collection.where(attributes)

Return an array of all the models in a collection that match the
passed
attributes
.
Useful for simple cases of
filter
.
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
var musketeers = friends.where({job: "Musketeer"});
alert(musketeers.length);
url
collection.url or collection.url()

Set the
url
property (or function) on a collection to reference
its location on the server.
Models within the collection will use
url

to construct URLs of their own.
var Notes = Backbone.Collection.extend({
url: '/notes'
});
// Or, something more sophisticated:
var Notes = Backbone.Collection.extend({
url: function() {
return this.document.url() + '/notes';
}
});
parse
collection.parse(response)

parse
is called by Backbone whenever a collection's models are
returned by the
server, in
fetch
.
The function is passed the raw
response
object, and should return
the
array of model attributes to be
added

to the collection. The default implementation is a
no-op, simply passing
through the JSON response. Override this if you need to work
with a
preexisting API, or better namespace your responses.
var Tweets = Backbone.Collection.extend({
// The Twitter Search API returns tweets under "results".
parse: function(response) {
return response.results;
}
});
2/5/13
Backbone.js
backbonejs.org
18/60
clone
collection.clone()

Returns a new instance of the collection with an identical list of models.
fetch
collection.fetch([options])

Fetch the default set of models for this collection from the server,
resetting the
collection when they arrive. The
options
hash takes
success
and
error

callbacks
which will be passed
(collection, response, options)

and
(collection, xhr,
options)
as arguments, respectively.
When the model data returns from the server,
the collection will be (efficiently)
reset
, unless you pass
{update: true}
,
in which case
it will use
update
to (intelligently)
merge the fetched models.
Delegates to
Backbone.sync

under the covers for custom persistence strategies and returns a
jqXHR
.
The server handler for
fetch
requests should return a JSON array of
models.
Backbone.sync = function(method, model) {
alert(method + ": " + model.url);
};
var Accounts = new Backbone.Collection;
Accounts.url = '/accounts';
Accounts.fetch();
The behavior of
fetch
can be customized by using the available
update
options. For
example, to fetch a
collection, getting an
"add"
event for every new model, and
a
"change"
event for every changed existing model, without
removing anything:
collection.fetch({update: true, remove: false})
jQuery.ajax
options can also be passed directly as
fetch
options,
so to fetch a specific
page of a paginated collection:
Documents.fetch({data: {page: 3}})
Note that
fetch
should not be used to populate collections on
page load — all models
needed at load time should already be
bootstrapped
in to place.
fetch
is
intended for
lazily-loading models for interfaces that are not needed
immediately: for example,
documents with collections of notes that may be
toggled open and closed.
create
collection.create(attributes, [options])

Convenience to create a new instance of a model within a collection.
Equivalent to
instantiating a model with a hash of attributes,
saving the model to the server, and
adding the model to the set after being
successfully created. Returns
the model, or
false
if a validation error prevented the
model from being created. In order for this to
work, you should set the
model
property of the collection.
The
create
method can
accept either an attributes hash or an
existing, unsaved model object.
Creating a model will cause an immediate
"add"
event to be
triggered on the
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
model. Pass
{wait: true}

if you'd like to wait for the server before adding the new
model to the collection.
var Library = Backbone.Collection.extend({
model: Book
});
var NYPL = new Library;
2/5/13
Backbone.js
backbonejs.org
19/60
var othello = NYPL.create({
title: "Othello",
author: "William Shakespeare"
});
Backbone.Router
Web applications often provide linkable, bookmarkable, shareable URLs for
important
locations in the app. Until recently, hash fragments
(
#page
) were used to provide these
permalinks, but with the
arrival of the History API, it's now possible to use standard
URLs (
/page
).
Backbone.Router
provides methods for routing client-side pages, and
connecting them to actions and events. For browsers which don't yet support
the
History API, the Router handles graceful fallback and transparent
translation to the
fragment version of the URL.
During page load, after your application has finished creating all of its routers,
be sure
to call
Backbone.history.start()
, or
Backbone.history.start({pushState: true})
to route the initial URL.
extend
Backbone.Router.extend(properties, [classProperties])

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
actions. Note that you'll want to avoid using a
leading slash in your route definitions:
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});
routes
router.routes

The routes hash maps URLs with parameters to functions on your router,
similar to the
View
's
events hash
.
Routes can contain parameter parts,
:param
, which match a
single URL
component between slashes; and splat parts
*splat
, which can match
any
number of URL components. Part of a route can be made optional by
surrounding it in
parentheses
(/:optional)
.
For example, a route of
"search/:query/p:page"
will match
a fragment of
#search/obama/p2
, passing
"obama"

and
"2"
to the action.
A route of
"file/*path"
will match
#file/nested/folder/file.txt
, passing
"nested/folder/file.txt"
to the action.
2/5/13
Backbone.js
backbonejs.org
20/60
A route of
"docs/:section(/:subsection)"
will match
#docs/faq
and
#docs/faq/installing
, passing
"faq"
to the action in the first case, and passing
"faq"

and
"installing"
to the action in the second.
When the visitor presses the back button, or enters a URL, and a particular
route is
matched, the name of the action will be fired as an
event
, so that other objects can
listen to the router,
and be notified. In the following example, visiting
#help/uploading
will fire a
route:help
event from the router.
routes: {
"help/:page": "help",
"download/*path": "download",
"folder/:name": "openFolder",
"folder/:name-:mode": "openFolder"
}
router.on("route:help", function(page) {
...
});
constructor / initialize
new Router([options])

When creating a new router, you may pass its
routes
hash directly as an option, if you
choose. All
options
will also be passed to your
initialize

function, if defined.
route
router.route(route, name, [callback])

Manually create a route for the router, The
route
argument may
be a
routing string
or
regular expression.
Each matching capture from the route or regular expression will be
passed as
an argument to the callback. The
name
argument will be triggered as
a
"route:name"
event whenever the route is matched.
If the
callback
argument is
omitted
router[name]
will be used
instead.
initialize: function(options) {
// Matches #page/10, passing "10"
this.route("page/:number", "page", function(number){ ... });
// Matches /117-a/b/c/open, passing "117-a/b/c" to this.open
this.route(/^(.*?)\/open$/, "open");
},
open: function(id) { ... }
navigate
router.navigate(fragment, [options])

Whenever you reach a point in your application that you'd like to save
as a URL, call
navigate
in order to update the URL.
If you wish to also call the route function, set the
trigger

option to
true
.
To update the URL without creating an entry in the browser's
history,
set the
replace
option to
true
.
openPage: function(pageNumber) {
this.document.pages.at(pageNumber).open();
this.navigate("page/" + pageNumber);
}
# Or ...
2/5/13
Backbone.js
backbonejs.org
21/60
app.navigate("help/troubleshooting", {trigger: true});
# Or ...
app.navigate("help/troubleshooting", {trigger: true, replace: true});
Backbone.history
History
serves as a global router (per frame) to handle
hashchange

events or
pushState
, match the appropriate route, and trigger callbacks. You shouldn't
ever
have to create one of these yourself — you should use the reference
to
Backbone.history
that will be created for you automatically if you make use
of
Routers
with
routes
.
pushState
support exists on a purely opt-in basis in Backbone.
Older browsers that
don't support
pushState
will continue to use
hash-based URL fragments, and if a hash
URL is visited by a
pushState
-capable browser, it will be transparently upgraded to
the
true URL. Note that using real URLs requires your web server to be
able to correctly
render those pages, so back-end changes are required
as well. For example, if you
have a route of
/documents/100
,
your web server must be able to serve that page, if
the browser
visits that URL directly. For full search-engine crawlability, it's best to
have
the server generate the complete HTML for the page ... but if it's a web
application, just
rendering the same content you would have for the root URL,
and filling in the rest with
Backbone Views and JavaScript works fine.
start
Backbone.history.start([options])

When all of your
Routers
have been created,
and all of the routes are set up properly,
call
Backbone.history.start()

to begin monitoring
hashchange
events, and
dispatching routes.
To indicate that you'd like to use HTML5
pushState
support in
your application, use
Backbone.history.start({pushState: true})
.
If you'd like to use
pushState
, but
have browsers that don't support
it natively use full page refreshes instead, you can
add
{hashChange: false}
to the options.
If your application is not being served from the root url
/
of your
domain, be sure to
tell History where the root really is, as an option:
Backbone.history.start({pushState:
true, root: "/public/search/"})
When called, if a route succeeds with a match for the current URL,
Backbone.history.start()
returns
true
. If no defined
route matches the current
URL, it returns
false
.
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
.
Because hash-based history in Internet Explorer relies on an
<iframe>
, be sure to
only call
start()
after the DOM
is ready.
$(function(){
new WorkspaceRouter();
new HelpPaneRouter();
Backbone.history.start({pushState: true});
2/5/13
Backbone.js
backbonejs.org
22/60
});
Backbone.sync
Backbone.sync
is the function that Backbone calls every time it
attempts to read or
save a model to the server. By default, it uses
(jQuery/Zepto).ajax
to make a
RESTful JSON request and returns a
jqXHR
. You can override
it in order to use a
different persistence strategy, such as WebSockets,
XML transport, or Local Storage.
The method signature of
Backbone.sync
is
sync(method, model, [options])
method
– the CRUD method (
"create"
,
"read"
,
"update"
, or
"delete"
)
model
– the model to be saved (or collection to be read)
options
– success and error callbacks, and all other jQuery request options
With the default implementation, when
Backbone.sync
sends up a request to save
a
model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
with
content-type
application/json
. When returning a JSON response,
send down the
attributes of the
model that have been changed by the server, and need
to be updated
on the client. When responding to a
"read"
request from a collection
(
Collection#fetch
), send down an array
of model attribute objects.
Whenever a model or collection begins a
sync
with the server, a
"request"
event is
emitted. If the request completes successfully
you'll get a
"sync"
event, and an
"error"
event if not.
The
sync
function may be overriden globally as
Backbone.sync
,
or at a finer-grained
level, by adding a
sync
function to a Backbone
collection or to an individual model.
The default
sync
handler maps CRUD to REST like so:
create → POST
/collection
read → GET
/collection[/id]
update → PUT
/collection/id
delete → DELETE
/collection/id
As an example, a Rails handler responding to an
"update"
call from
Backbone
might
look like this:
(In real code, never use
update_attributes
blindly, and always whitelist
the attributes
you allow to be changed.)
def update
account = Account.find params[:id]
account.update_attributes params
render :json => account
end
One more tip for integrating Rails versions prior to 3.1 is to disable
the default
namespacing for
to_json
calls on models by setting
ActiveRecord::Base.include_root_in_json = false
ajax
Backbone.ajax = function(request) { ... };

2/5/13
Backbone.js
backbonejs.org
23/60
If you want to use a custom AJAX function, or your endpoint doesn't support
the
jQuery.ajax
API
and you need to tweak things, you can do so by setting
Backbone.ajax
.
emulateHTTP
Backbone.emulateHTTP = true

If you want to work with a legacy web server that doesn't support Backbone's
default
REST/HTTP approach, you may choose to turn on
Backbone.emulateHTTP
.
Setting this
option will fake
PUT
and
DELETE
requests with
a HTTP
POST
, setting the
X-HTTP-
Method-Override
header
with the true method. If
emulateJSON
is also on, the true
method
will be passed as an additional
_method
parameter.
Backbone.emulateHTTP = true;
model.save(); // POST to "/collection/id", with "_method=PUT" + header.
emulateJSON
Backbone.emulateJSON = true

If you're working with a legacy web server that can't handle requests
encoded as
application/json
, setting
Backbone.emulateJSON = true;

will cause the JSON to be
serialized under a
model
parameter, and
the request to be made with a
application/x-www-form-urlencoded

mime type, as if from an HTML form.
Backbone.View
Backbone views are almost more convention than they are code — they
don't
determine anything about your HTML or CSS for you, and can be used
with any
JavaScript templating library.
The general idea is to organize your interface into logical
views,
backed by models, each of which can be updated independently when the
model
changes, without having to redraw the page. Instead of digging into
a JSON object,
looking up an element in the DOM, and updating the HTML by hand,
you can bind your
view's
render
function to the model's
"change"

event — and now everywhere that
model data is displayed in the UI, it is always immediately up to date.
extend
Backbone.View.extend(properties, [classProperties])

Get started with views by creating a custom view class. You'll want to
override the
render
function, specify your
declarative
events
, and perhaps the
tagName
,
className
, or
id
of the View's root
element.
var DocumentRow = Backbone.View.extend({
tagName: "li",
className: "document-row",
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
}
render: function() {
...
2/5/13
Backbone.js
backbonejs.org
24/60
}
});
Properties like
tagName
,
id
,
className
,
el
, and
events
may also be defined as a
function, if
you want to wait to define them until runtime.
constructor / initialize
new View([options])

When creating a new View, the options you pass — after being merged
into any default
options already present on the view —
are attached to the view as
this.options
for
future reference.
There are several special
options that, if passed, will be attached
directly to the view:
model
,
collection
,
el
,
id
,
className
,
tagName
and
attributes
.
If the view defines an
initialize
function, it will be called when
the view is
first created. If you'd like to create a view that references
an element
already
in the
DOM, pass in the element as an option:
new View({el: existingElement})
var doc = Documents.first();
new DocumentRow({
model: doc,
id: "document-row-" + doc.id
});
el
view.el

All views have a DOM element at all times (the
el
property),
whether they've already
been inserted into the page or not. In this
fashion, views can be rendered at any time,
and inserted into the DOM all
at once, in order to get high-performance UI rendering
with as few
reflows and repaints as possible.
this.el
is created from the
view's
tagName
,
className
,
id
and
attributes
properties,
if specified. If not,
el
is an
empty
div
.
var ItemView = Backbone.View.extend({
tagName: 'li'
});
var BodyView = Backbone.View.extend({
el: 'body'
});
var item = new ItemView();
var body = new BodyView();
alert(item.el + ' ' + body.el);
$el
view.$el

A cached jQuery (or Zepto) object for the view's element. A handy
reference instead of
re-wrapping the DOM element all the time.
view.$el.show();
listView.$el.append(itemView.el);
setElement
view.setElement(element)

If you'd like to apply a Backbone view to a different DOM element, use
setElement
,
which will also create the cached
$el
reference
and move the view's delegated events
2/5/13
Backbone.js
backbonejs.org
25/60
from the old element to the new one.
attributes
view.attributes

A hash of attributes that will be set as HTML DOM element attributes on the
view's
el
(id, class, data-properties, etc.), or a function that
returns such a hash.
$ (jQuery or Zepto)
view.$(selector)

If jQuery or Zepto is included on the page, each view has a
$
function that runs queries
scoped within the view's element. If you use this
scoped jQuery function, you don't have
to use model ids as part of your query
to pull out specific elements in a list, and can
rely much more on HTML class
attributes. It's equivalent to running:
view.$el.find(selector)
ui.Chapter = Backbone.View.extend({
serialize : function() {
return {
title: this.$(".title").text(),
start: this.$(".start-page").text(),
end: this.$(".end-page").text()
};
}
});
render
view.render()

The default implementation of
render
is a no-op. Override this
function with your code
that renders the view template from model data,
and updates
this.el
with the new
HTML. A good
convention is to
return this
at the end of
render
to
enable chained
calls.
var Bookmark = Backbone.View.extend({
template: _.template(…),
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
Backbone is agnostic with respect to your preferred method of HTML templating.
Your
render
function could even munge together an HTML string, or use
document.createElement
to generate a DOM tree. However, we suggest
choosing a
nice JavaScript templating library.
Mustache.js
,
Haml-js
, and
Eco
are all fine
alternatives.
Because
Underscore.js
is already on the page,
_.template

is available,
and is an excellent choice if you prefer simple
interpolated-JavaScript style templates.
Whatever templating strategy you end up with, it's nice if you
never

have to put strings
of HTML in your JavaScript. At DocumentCloud, we
use
Jammit
in order
to package up
JavaScript templates stored in
/app/views
as part
of our main
core.js
asset
package.
remove
view.remove()

Removes a view from the DOM, and calls
stopListening
to remove any bound
events
that the view has
listenTo
'd.
2/5/13
Backbone.js
backbonejs.org
26/60
delegateEvents
delegateEvents([events])

Uses jQuery's
on
function to provide declarative callbacks
for DOM events within a
view.
If an
events
hash is not passed directly, uses
this.events

as the source.
Events are written in the format
{"event selector": "callback"}
.
The callback may
be either the name of a method on the view, or a direct
function body.
Omitting the
selector
causes the event to be bound to the view's
root element (
this.el
). By
default,
delegateEvents
is called
within the View's constructor for you, so if you have a
simple
events

hash, all of your DOM events will always already be connected, and you
will
never have to call this function yourself.
The
events
property may also be defined as a function that returns
an
events
hash,
to make it easier to programmatically define your
events, as well as inherit them from
parent views.
Using
delegateEvents
provides a number of advantages over manually
using jQuery
to bind events to child elements during
render
. All attached
callbacks are bound to the
view before being handed off to jQuery, so when
the callbacks are invoked,
this
continues to refer to the view object. When
delegateEvents
is run again, perhaps with
a different
events

hash, all callbacks are removed and delegated afresh — useful for
views which need to behave differently when in different modes.
A view that displays a document in a search result might look
something like this:
var DocumentView = Backbone.View.extend({
events: {
"dblclick" : "open",
"click .icon.doc" : "select",
"contextmenu .icon.doc" : "showMenu",
"click .show_notes" : "toggleNotes",
"click .title .lock" : "editAccessLevel",
"mouseover .title .date" : "showTooltip"
},
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
},
open: function() {
window.open(this.model.get("viewer_url"));
},
select: function() {
this.model.set({selected: true});
},
...
});
undelegateEvents
undelegateEvents()

Removes all of the view's delegated events. Useful if you want to disable
or remove a
view from the DOM temporarily.
Utility
2/5/13
Backbone.js
backbonejs.org
27/60
Backbone.noConflict
var backbone = Backbone.noConflict();

Returns the
Backbone
object back to its original value. You can
use the return value of
Backbone.noConflict()
to keep a local
reference to Backbone. Useful for embedding
Backbone on third-party
websites, where you don't want to clobber the existing
Backbone.
var localBackbone = Backbone.noConflict();
var model = localBackbone.Model.extend(...);
Backbone.$
Backbone.$ = $;

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.
Examples
The list of examples that follows, while long, is not exhaustive. If you've
worked on an
app that uses Backbone, please add it to the
wiki page of Backbone apps
.
Jérôme Gravel-Niquet
has contributed a
Todo List application

that is bundled in the
repository as Backbone example. If you're wondering
where to get started with
Backbone in general, take a moment to
read through the annotated source
. The app
uses a
LocalStorage adapter

to transparently save all of your todos within your
browser, instead of
sending them to a server. Jérôme also has a version hosted at
localtodos.com
that uses a
MooTools-backed version of Backbone

instead of jQuery.
Todos
DocumentCloud
The
DocumentCloud workspace

is built on Backbone.js, with
Documents
,
Projects
,
Notes
, and
Accounts
all as Backbone models and collections.
If you're interested in
history — both Underscore.js and Backbone.js
were originally extracted from the
2/5/13
Backbone.js
backbonejs.org
28/60
DocumentCloud codebase, and packaged
into standalone JS libraries.
DocumentCloud Workspace
USA Today
USA Today
takes advantage of the modularity of
Backbone's data/model lifecycle —
which makes it simple to create, inherit,
isolate, and link application objects — to keep
the codebase both manageable and efficient.
The new website also makes heavy use
of the Backbone Router to control the
page for both pushState-capable and legacy
browsers.
Finally, the team took advantage of Backbone's Event module to create a
PubSub API that allows third parties and analytics packages to hook into the
heart of
the app.
2/5/13
Backbone.js
backbonejs.org
29/60
USA Today
Rdio
New Rdio
was developed from the ground
up with a component based framework
based on Backbone.js. Every component
on the screen is dynamically loaded and
rendered, with data provided by the
Rdio API
. When changes are pushed,
every
component can update itself without reloading the page or interrupting
the user's
music. All of this relies on Backbone's views and models,
and all URL routing is handled
by Backbone's Router. When data changes are
signaled in realtime, Backbone's
Events notify the interested components
in the data changes. Backbone forms the core
of the new, dynamic, realtime
Rdio web and
desktop
applications.
Rdio
2/5/13
Backbone.js
backbonejs.org
30/60
LinkedIn Mobile
LinkedIn
used Backbone.js to create
its
next-generation HTML5 mobile web app
.
Backbone made it easy to keep the app modular, organized and extensible so
that it
was possible to program the complexities of LinkedIn's user experience.
The app also
uses
Zepto
,
Underscore.js
,
SASS
,
iScroll
,
HTML5 LocalStorage and Canvas. The tech
team blogged about
their experiences using LocalStorage

to improve mobile
performance.
LinkedIn Mobile
Hulu
Hulu
used Backbone.js to build its next
generation online video experience. With
Backbone as a foundation, the
web interface was rewritten from scratch so that all page
content can
be loaded dynamically with smooth transitions as you navigate.
Backbone
makes it easy to move through the app quickly without the
reloading of scripts and
embedded videos, while also offering models and
collections for additional data
manipulation support.
Hulu
Flow
MetaLab
used Backbone.js to create
Flow
, a task management app for teams. The
workspace relies on Backbone.js to construct task views, activities, accounts,
folders,
projects, and tags. You can see the internals under
window.Flow
.
2/5/13
Backbone.js
backbonejs.org
31/60
Flow
Gilt Groupe
Gilt Groupe
uses Backbone.js to build multiple
applications across their family of sites.
Gilt's mobile website
uses Backbone and
Zepto.js
to create a blazing-fast
shopping
experience for users on-the-go, while
Gilt Live
combines Backbone with
WebSockets to
display the items that customers are buying in real-time. Gilt's search
functionality also
uses Backbone to filter and sort products efficiently
by moving those actions to the
client-side.
Gilt Groupe
NewsBlur
2/5/13
Backbone.js
backbonejs.org
32/60
NewsBlur
is an RSS feed reader and
social news network with a fast and responsive UI
that feels like a
native desktop app. Backbone.js was selected for
a major rewrite and
transition from spaghetti code

because of its powerful yet simple feature set, easy
integration, and large
community. If you want to poke around under the hood, NewsBlur
is also entirely
open-source
.
Newsblur
WordPress.com
WordPress.com
is the software-as-a-service
version of
WordPress
. It uses Backbone.js
Models, Collections, and Views in its
Notifications system
.
Backbone.js was selected
because it was easy to fit into the structure of the application, not the
other way
around.
Automattic

(the company behind WordPress.com) is integrating Backbone.js
into the
Stats tab and other features throughout the homepage.
WordPress.com Notifications
Foursquare
2/5/13
Backbone.js
backbonejs.org
33/60
Foursquare is a fun little startup that helps you meet up with friends,
discover new
places, and save money. Backbone Models are heavily used in
the core JavaScript API
layer and Views power many popular features like
the
homepage map
and
lists
.
Foursquare
Bitbucket
Bitbucket
is a free source code hosting
service for Git and Mercurial. Through its
models and collections,
Backbone.js has proved valuable in supporting Bitbucket's
REST API
, as well as newer
components such as in-line code comments and approvals
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
existing DOM
trees and insert new ones.
Bitbucket
Disqus
2/5/13
Backbone.js
backbonejs.org
34/60
Disqus
chose Backbone.js to power the
latest version of their commenting widget.
Backbone’s small
footprint and easy extensibility made it the right choice for Disqus’
distributed web application, which is hosted entirely inside an iframe and
served on
thousands of large web properties, including IGN, Wired, CNN, MLB, and more.
Disqus
Khan Academy
Khan Academy
is on a mission to
provide a free world-class education to anyone
anywhere. With thousands of
videos, hundreds of JavaScript-driven exercises, and big
plans for the
future, Khan Academy uses Backbone to keep frontend code modular and
organized.
User profiles and goal setting are implemented with Backbone,
jQuery
and
Handlebars
, and most new feature
work is being pushed to the client side, greatly
increasing the quality of
the API
.
2/5/13
Backbone.js
backbonejs.org
35/60
Khan Academy
Do
Do
is a social productivity app that makes it
easy to work on tasks, track projects, and
take notes with your team.
The
Do.com
web application was built from the
ground up to
work seamlessly on your smartphone, tablet and computer. The
team used Backbone,
CoffeeScript
and
Handlebars
to build a full-featured
app in record time and rolled their
own extensions for complex navigation
and model sync support.
Do
IRCCloud
2/5/13
Backbone.js
backbonejs.org
36/60
IRCCloud

is an always-connected IRC client that you use in your
browser — often
leaving it open all day in a tab.
The sleek web interface communicates with an
Erlang
backend via websockets and the
IRCCloud API
.
It makes heavy use of Backbone.js
events, models, views and routing to keep
your IRC conversations flowing in real time.
IRCCloud
Pitchfork
Pitchfork
uses Backbone.js to power
its site-wide audio player,
Pitchfork.tv
,
location
routing, a write-thru page fragment cache, and more. Backbone.js
(and
Underscore.js
)
helps the team
create clean and modular components,
move very quickly, and focus on
the site, not the spaghetti.
Pitchfork
Spin
2/5/13
Backbone.js
backbonejs.org
37/60
Spin
pulls in the
latest news stories
from
their internal API onto their site using
Backbone models and collections, and a
custom
sync
method. Because the music
should never stop playing,
even as you click through to different "pages", Spin uses a
Backbone router
for navigation within the site.
Spin
Walmart Mobile
Walmart
used Backbone.js to create the new version
of
their mobile web application
and
created two new frameworks in the process.
Thorax
provides mixins, inheritable
events, as well as model and collection view bindings that integrate directly with
Handlebars
templates.
Lumbar
allows the application to be
split into modules which can
be loaded on demand, and creates platform specific builds
for the portions of the web
application that are embedded in Walmart's native Android
and iOS applications.
2/5/13
Backbone.js
backbonejs.org
38/60
Walmart Mobile
Groupon Now!
Groupon Now!
helps you find
local deals that you can buy and use right now. When
first developing
the product, the team decided it would be AJAX heavy with smooth
transitions
between sections instead of full refreshes, but still needed to be fully
linkable and shareable. Despite never having used Backbone before, the
learning
curve was incredibly quick — a prototype was hacked out in an
afternoon, and the
team was able to ship the product in two weeks.
Because the source is minimal and
understandable, it was easy to
add several Backbone extensions for Groupon Now!:
changing the router
to handle URLs with querystring parameters, and adding a simple
in-memory store for caching repeated requests for the same data.
2/5/13
Backbone.js
backbonejs.org
39/60
Groupon Now!
Basecamp
37Signals
chose Backbone.js to create
the
calendar feature
of its
popular project
management software
Basecamp
.
The Basecamp Calendar uses Backbone.js models
and views in conjunction with the
Eco
templating system to
present a polished, highly
interactive group scheduling interface.
Basecamp Calendar
Slavery Footprint
Slavery Footprint

allows consumers to visualize how their consumption habits are
connected to modern-day slavery and provides them with an opportunity
to have a
deeper conversation with the companies that manufacture the
goods they purchased.
2/5/13
Backbone.js
backbonejs.org
40/60
Based in Oakland, California, the Slavery Footprint team works to engage
individuals,
groups, and businesses to build awareness for and create
deployable action against
forced labor, human trafficking, and modern-day
slavery through online tools, as well
as off-line community education and
mobilization programs.
Slavery Footprint
Stripe
Stripe
provides an API for accepting
credit cards on the web. Stripe's
management
interface
was recently
rewritten from scratch in Coffeescript using Backbone.js as the
primary
framework,
Eco
for templates,
Sass
for stylesheets, and
Stitch
to package
everything together as
CommonJS
modules. The new app uses
Stripe's API
directly for
the
majority of its actions; Backbone.js models made it simple to map
client-side models
to their corresponding RESTful resources.
Stripe
Airbnb
2/5/13
Backbone.js
backbonejs.org
41/60
Airbnb
uses Backbone in many of its products.
It started with
Airbnb Mobile Web

(built
in six weeks by a team of three) and has since grown to
Wish Lists
,
Match
,
Search
,
Communities, Payments, and
Internal Tools.
Airbnb
Diaspora
Diaspora
is a distributed social
network, formed from a number of independently
operated
pods
.
You own your personal data, and control with whom you share.
All of
Diaspora is
open-source

code, built with
Rails
and Backbone.js.
Diaspora
2/5/13
Backbone.js
backbonejs.org
42/60
SoundCloud Mobile
SoundCloud
is the leading sound sharing
platform on the internet, and Backbone.js
provides the foundation for
SoundCloud Mobile
. The project uses
the public
SoundCloud
API

as a data source (channeled through a nginx proxy),
jQuery templates
for the rendering,
Qunit
and
PhantomJS
for
the testing suite. The JS code, templates
and CSS are built for the
production deployment with various Node.js tools like
ready.js
,
Jake
,
jsdom
.
The
Backbone.History
was modified to support the HTML5
history.pushState
.
Backbone.sync
was extended with an additional SessionStorage
based cache
layer.
SoundCloud
Art.sy
Art.sy
is a place to discover art you'll
love. Art.sy is built on Rails, using
Grape
to serve
a robust
JSON API
. The main site is a single page
app written in Coffeescript and uses
Backbone to provide structure around
this API. An admin panel and partner CMS have
also been extracted into
their own API-consuming Backbone projects.
2/5/13
Backbone.js
backbonejs.org
43/60
Art.sy
Pandora
When
Pandora
redesigned
their site in HTML5, they chose Backbone.js to help
manage the user interface and interactions. For example, there's a model
that
represents the "currently playing track", and multiple views that
automatically update
when the current track changes. The station list is a
collection, so that when stations
are added or changed, the UI stays up to date.
Pandora
Inkling
2/5/13
Backbone.js
backbonejs.org
44/60
Inkling
is a cross-platform way to
publish interactive learning content.
Inkling for Web
uses Backbone.js
to make hundreds of complex books — from student textbooks to
travel guides and
programming manuals — engaging and accessible on the web.
Inkling supports
WebGL-enabled 3D graphics, interactive assessments, social sharing,
and a system for running practice code right
in the book, all within a single page
Backbone-driven app. Early on, the
team decided to keep the site lightweight by using
only Backbone.js and
raw JavaScript. The result? Complete source code weighing in at
a mere
350kb with feature-parity across the iPad, iPhone and web clients.
Give it a try
with
this excerpt from JavaScript: The Definitive Guide
.
Inkling
Code School
Code School
courses teach people
about various programming topics like
CoffeeScript
,
CSS, Ruby on Rails,
and more. The new Code School course
challenge page

is built
from the ground up on Backbone.js, using
everything it has to offer: the router,
collections, models, and complex
event handling. Before, the page was a mess of
jQuery
DOM manipulation
and manual Ajax calls. Backbone.js helped introduce a new
way to
think about developing an organized front-end application in Javascript.
2/5/13
Backbone.js
backbonejs.org
45/60
Code School
CloudApp
CloudApp
is simple file and link
sharing for the Mac. Backbone.js powers the web tools
which consume the
documented API

to manage Drops. Data is either pulled manually
or pushed by
Pusher
and fed to
Mustache
templates for
rendering. Check out the
annotated source code

to see the magic.
CloudApp
SeatGeek
2/5/13
Backbone.js
backbonejs.org
46/60
SeatGeek
's stadium ticket maps were originally
developed with
Prototype.js
. Moving to
Backbone.js and
jQuery
helped organize
a lot of the UI code, and the increased
structure has made adding features
a lot easier. SeatGeek is also in the process of
building a mobile
interface that will be Backbone.js from top to bottom.
SeatGeek
Easel
Easel
is an in-browser, high fidelity web
design tool that integrates with your design and
development
process. The Easel team uses CoffeeScript, Underscore.js and
Backbone.js for
their
rich visual editor
as well as other