
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 pr…

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, or add pages to the wiki.
- Backbone is an open-source component of DocumentCloud. *
Downloads & Dependencies (Right-click, and use "Save As")
Backbone’s only hard dependency is Underscore.js ( >= 1.8.3). For RESTful persistence and DOM manipulation with Backbone.View, include jQuery ( >= 1.11.0). (Mimics of the Underscore and jQuery APIs, such as Lodash and Zepto, will also tend to work, with varying degrees of compatibility.)
Getting Started
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 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.
Philosophically, Backbone is an attempt to discover the minimal set of data-structuring (models and collections) and user interface (views and URLs) primitives that are generally useful when building web applications with JavaScript. In an ecosystem where overarching, decides-everything-for-you frameworks are commonplace, and many libraries require your site to be reorganized to suit their look, feel, and default behavior — Backbone should continue to be a tool that gives you the freedom to design the full experience of your web application.
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 code examples in this documentation are runnable, because Backbone is included on this page. Click the play button to execute them.
Models and Views
The single most important thing that Backbone can help you with is keeping your business logic separate from your user interface. When the two are entangled, change is hard; when logic doesn’t depend on UI, your interface becomes easier to work with.
Model
- Orchestrates data and business logic.
- Loads and saves data from the server.
- Emits events when data changes.
View
- Listens for changes and renders UI.
- Handles user input and interactivity.
- Sends captured input to the model.
A Model manages an internal table of data attributes, and triggers "change" 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 reusable objects containing all of the helpful functions for manipulating their particular bit of data. Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.
A View is an atomic chunk of user interface. It often renders the data from a specific model, or number of models — but views can also be data-less chunks of UI that stand alone. Models should be generally unaware of views. Instead, views listen to the model "change" events, and react or re-render themselves appropriately.
Collections
A Collection helps you deal with a group of related models, handling the loading and 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, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection.
API Integration
Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection with the url of your resource endpoint:
var Books = Backbone.Collection.extend({
url: '/books'
});
The Collection and Model components together form a direct mapping of REST resources using the following methods:
GET /books/ .... collection.fetch();
POST /books/ .... collection.create();
GET /books/1 ... model.fetch();
PUT /books/1 ... model.save();
DEL /books/1 ... model.destroy();
When fetching raw JSON data from an API, a Collection will automatically populate itself with data formatted as an array, while a Model will automatically populate itself with data formatted as an object:
[{"id": 1}] ..... populates a Collection with one model.
{"id": 1} ....... populates a Model with one attribute.
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 returns the real data array wrapped in metadata:
{
"page": 1,
"limit": 10,
"total": 2,
"books": [
{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
]
}
In the above example data, a Collection should populate using the "books" array 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:
var Books = Backbone.Collection.extend({
url: '/books',
parse: function(data) {
return data.books;
}
});
View Rendering
Each View manages the rendering and user interaction within its own DOM element. If you’re strict about not allowing views to reach outside of themselves, it helps keep your interface flexible — allowing views to be rendered in isolation in any place where they might be needed.
Backbone remains unopinionated about the process used to render View objects and their subviews into UI: you define how your models get translated into HTML (or SVG, or Canvas, or something even more exotic). It could be as prosaic as a simple Underscore template, or as fancy as the React virtual DOM. Some basic approaches to rendering views can be found in the Backbone primer.
Routing with URLs
In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share. Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.
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)
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", ...);
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:author": authorPane.update,
"change:title change:subtitle": titleView.update,
"destroy": bookView.remove
});
To supply a context value for this when the callback is invoked, pass the optional last argument: model.on(‘change’, this.render, this) or model.on({change: this.render}, this).
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.
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.
object.once(event, callback, [context])
Just like on, but causes the bound callback to fire only once before being removed. Handy for saying "the next time that X happens, do this". When multiple events are passed in using the space separated syntax, the event will fire once for every event you passed in, not once for a combination of all events
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, object), is that listenTo allows the object to keep track of the events, and they can be removed all at once later on. The callback will always be called with object as context.
view.listenTo(model, 'change', view.render);
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);
object.listenToOnce(other, event, callback)
Just like listenTo, but causes the bound callback to fire only once before being removed.
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.
- "update" (collection, options) — single event triggered after any number of models have been added, removed or changed in a collection.
- "reset" (collection, options) — when the collection’s entire contents have been reset.
- "sort" (collection, options) — when the collection has been re-sorted.
- "change" (model, options) — when a model’s attributes have changed.
- "changeId" (model, previousId, options) — when the model’s id has been updated.
- "change:[attribute]" (model, value, options) — when a specific attribute has been updated.
- "destroy" (model, collection, options) — when a model is destroyed.
- "request" (model_or_collection, xhr, options) — when a model or collection has started a request to the server.
- "sync" (model_or_collection, response, options) — when a model or collection has been successfully synced with the server.
- "error" (model_or_collection, xhr, options) — when a model’s or collection’s request to the server has failed.
- "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" (route, params) — Fired by the router when any route has been matched.
- "route" (router, route, params) — Fired by history when any route has been matched.
- "notfound" () — Fired by history when no route could be matched.
- "all" — this special event fires for any triggered event, passing the event name as the first argument followed by all trigger arguments.
Generally speaking, when calling a function that emits an event (model.set, collection.add, and so on...), if you’d like to prevent the event from being triggered, you may pass {silent: true} as an option. Note that this is rarely, perhaps even never, a good idea. Passing through a specific flag in the options for your event callback to look at, and choose to ignore, will usually work out better.
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 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();
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:
var Note = Backbone.Model.extend({
set: function(attributes, options) {
Backbone.Model.prototype.set.apply(this, arguments);
...
}
});
new Model([attributes], [options])
For use with models as ES classes. If you define a preinitialize method, it will be invoked when the Model is first created, before any instantiation logic is run for the Model.
class Country extends Backbone.Model {
preinitialize({countryCode}) {
this.name = COUNTRY_NAMES[countryCode];
}
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.
var Library = Backbone.Model.extend({
constructor: function() {
this.books = new Books();
Backbone.Model.apply(this, arguments);
},
parse: function(data, options) {
this.books.reset(data.books);
return data.library;
}
});
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 normally created automatically when you first add a model to a collection. Note that the reverse is not true, as passing this option to the constructor will not automatically add the model to the collection. Useful, sometimes.
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.
model.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")
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 on the model. 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");
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'));
model.has(attribute)
Returns true if the attribute is set to a non-null or non-undefined value.
if (note.has("title")) {
...
}
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.
model.clear([options])
Removes all attributes from the model, including the id attribute. Fires a "change" event unless silent is passed as an option.
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. model.id should not be manipulated directly, it should be modified only via model.set('id', …). Models can be retrieved by id from collections, and the id is used to generate model URLs by default.
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. If you set idAttribute, you may also want to override cidPrefix.
var Meal = Backbone.Model.extend({
idAttribute: "_id"
});
var cake = new Meal({ _id: 1, name: "Cake" });
alert("Cake id: " + cake.id);
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.
model.cidPrefix
If your model has an id that is anything other than an integer or a UUID, there is the possibility that it might collide with its cid. To prevent this, you can override the prefix that cids start with.
// If both lengths are 2, refresh the page before running this example.
var clashy = new Backbone.Collection([
{id: 'c2'},
{id: 'c1'},
]);
alert('clashy length: ' + clashy.length);
var ClashFree = Backbone.Model.extend({cidPrefix: 'm'});
var clashless = new Backbone.Collection([
{id: 'c3'},
{id: 'c2'},
], {model: ClashFree});
alert('clashless length: ' + clashless.length);
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.
model.changed
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 internally maintained by set. A copy of changed can be acquired from changedAttributes.
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.
If you set a value for the model’s idAttribute, you should define the defaults as a function that returns a different, universally unique id on every invocation. Not doing so would likely prevent an instance of Backbone.Collection from correctly identifying model hashes and is almost certainly a mistake, unless you never add instances of the model class to a collection.
model.toJSON([options])
Return a shallow 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));
model.sync(method, model, [options])
Uses Backbone.sync to persist the state of a model to the server. Can be overridden for custom behavior.
model.fetch([options])
Merges the model’s state with attributes fetched 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. Triggers a "change" event if the server’s state differs from the current attributes. fetch accepts success and error callbacks in the options hash, which are both passed (model, response, options) as arguments.
// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
channel.fetch();
}, 10000);
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.set('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 will be passed the arguments (model, response, options). 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(){ ... }});
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 will be passed (model, response, options). 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.
book.destroy({success: function(model, response) {
...
}});
Backbone proxies to Underscore.js to provide 9 object functions on Backbone.Model. They aren’t all documented here, but you can take a look at the Underscore documentation for the full details…
user.pick('first_name', 'last_name', 'email');
chapters.keys().join(', ');
model.validate(attributes, options)
This method is left undefined and you’re encouraged to override it with any custom validation logic you have that can be performed in JavaScript. 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.
By default save checks validate before setting any attributes but you may also tell set to validate the new attributes by passing {validate: true} as an option. The validate method receives the model attributes as well as any options passed to set or save, if validate returns an error, save does not continue, the model attributes are not modified on the server, an "invalid" event is triggered, and the validationError property is set 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.
model.validationError
The value returned by validate during the last failed validation.
model.isValid(options)
Run validate to check the model state.
The validate method receives the model attributes as well as any options passed to isValid, if validate returns an error an "invalid" event is triggered, and the error is set on the model in the validationError property.
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.set({
start: 15,
end: 10
});
if (!one.isValid()) {
alert(one.get("title") + " " + one.validationError);
}
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"
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());
model.parse(response, options)
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
model.clone()
Returns a new instance of the model with identical attributes.
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.
model.hasChanged([attribute])
Has the model changed since its last set? 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")) {
...
}
});
model.changedAttributes([attributes])
Retrieve a hash of only the model’s attributes that have changed since the last set, or false if there are none. 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.
model.previous(attribute)
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"});
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", ...)
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.
collection.model([attrs], [options])
Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects (and arrays) and options to add, create, and reset, and the attributes will be converted into a model of the proper type using the provided options, if any.
var Library = Backbone.Collection.extend({
model: Book
});
A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.
var Library = Backbone.Collection.extend({
model: function(attrs, options) {
if (condition) {
return new PublicDocument(attrs, options);
} else {
return new PrivateDocument(attrs, options);
}
}
});
collection.modelId(attrs, idAttribute)
Override this method to return the value the collection will use to identify a model given its attributes. Useful for combining models from multiple tables with different idAttribute values into a single collection.
By default returns the value of the given idAttribute within the attrs, or failing that, id. If your collection uses a model factory and the id ranges of those models might collide, you must override this method.
var Library = Backbone.Collection.extend({
modelId: function(attrs) {
return attrs.type + attrs.id;
}
});
var library = new Library([
{type: 'dvd', id: 1},
{type: 'vhs', id: 1}
]);
var dvdId = library.get('dvd1').id;
var vhsId = library.get('vhs1').id;
alert('dvd: ' + dvdId + ', vhs: ' + vhsId);
new Backbone.Collection([models], [options])
For use with collections as ES classes. If you define a preinitialize method, it will be invoked when the Collection is first created and before any instantiation logic is run for the Collection.
class Library extends Backbone.Collection {
preinitialize() {
this.on("add", function() {
console.log("Add model event got fired!");
});
}
}
new Backbone.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. There are a couple of options that, if provided, are attached to the collection directly: model and comparator.
Pass null for models to create an empty Collection with options.
var tabs = new TabSet([tab1, tab2, tab3]);
var spaces = new Backbone.Collection(null, {
model: Space
});
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the collection.
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.
collection.toJSON([options])
Return an array containing the attributes hash of each model (via toJSON) 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));
collection.sync(method, collection, [options])
Uses Backbone.sync to persist the state of a collection to the server. Can be overridden for custom behavior.
Backbone proxies to Underscore.js to provide 46 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…
Most methods can take an object or string to support model-attribute-style predicates or a function that receives the model instance as an argument.
- forEach (each)
- map (collect)
- reduce (foldl, inject)
- reduceRight (foldr)
- find (detect)
- findIndex
- findLastIndex
- filter (select)
- reject
- every (all)
- some (any)
- contains (includes)
- invoke
- max
- min
- sortBy
- groupBy
- shuffle
- toArray
- size
- first (head, take)
- initial
- rest (tail, drop)
- last
- without
- indexOf
- lastIndexOf
- isEmpty
- chain
- difference
- sample
- partition
- countBy
- indexBy
books.each(function(book) {
book.publish();
});
var titles = books.map("title");
var publishedBooks = books.filter({published: true});
var alphabetical = books.sortBy(function(book) {
return book.author.get("name").toLowerCase();
});
var randomThree = books.sample(3);
collection.add(models, [options])
Add a model (or an array of models) to the collection, firing an "add" event for each model, and an "update" event afterwards. This is a variant of set with the same options and return value, but it always adds and never removes. 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.
collection.remove(models, [options])
Remove a model (or an array of models) from the collection, and return them. Each model can be a Model instance, an id string or a JS object, any value acceptable as the id argument of collection.get. Fires a "remove" event for each model, and a single "update" event afterwards, unless {silent: true} is passed. The model’s index before removal is available to listeners as options.index.
collection.reset([models], [options])
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 on completion, and without triggering any add or remove events on any models. Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels.
Pass null for models to empty your Collection with options.
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.
collection.set(models, [options])
The set method performs 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, with a single "update" event at the end. Returns the touched models in the collection. If you’d like to customize this behavior, you can change it with options: {add: false}, {remove: false}, or {merge: false}.
If a model property is defined, you may also pass raw attributes objects and options, and have them be vivified as instances of the model using the provided options. If you set a comparator, the collection will automatically sort itself and trigger a "sort" event, unless you pass {sort: false} or use the {at: index} option. Pass {at: index} to splice the model(s) into the collection at the specified index.
var vanHalen = new Backbone.Collection([eddie, alex, stone, roth]);
vanHalen.set([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.
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);
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. When passed a negative index, it will retrieve the model from the back of the collection.
collection.push(model, [options])
Like add, but always adds a model at the end of the collection and never sorts.
collection.pop([options])
Remove and return the last model from a collection. Takes the same options as remove.
collection.unshift(model, [options])
Like add, but always adds a model at the beginning of the collection and never sorts.
collection.shift([options])
Remove and return the first model from a collection. Takes the same options as remove.
collection.slice(begin, end)
Return a shallow copy of this collection’s models, using the same options as native Array#slice.
collection.length
Like an array, a Collection maintains a length property, counting the number of models it contains.
collection.comparator
By default there is no comparator for a collection. If you define a comparator, it will be used to sort the collection any time a model is added. 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 that Backbone depends on the arity of your comparator function to determine between the two styles, so be careful if your comparator function is bound.
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 = '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.
collection.sort([options])
Force a collection to re-sort itself. Note that a collection with a comparator will sort itself automatically 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.
collection.pluck(attribute)
Pluck an attribute from each model in the co