Backbone.js

Backbone supplies structure to JavaScript-heavy 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 application 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.

Backbone is an open-source component of DocumentCloud.

Downloads & Dependencies (Right-click, and use "Save As")

Development Version (0.1.1) 21kb, Uncompressed with Comments
Production Version (0.1.1) 2kb, Packed and Gzipped

Backbone's only hard dependency is Underscore.js. For RESTful persistence, and DOM manipulation with Backbone.View, it's highly recommended to include jQuery, and json2.js (both of which you may already have on the page).

Introduction

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

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 data are notified of the event, causing them to re-render. You don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves.

How is this different than SproutCore or Cappuccino?

This question is frequently asked, and all three projects apply general Model-View-Controller principles to JavaScript applications. However, there isn't much basis for comparison. SproutCore and Cappuccino provide rich UI widgets, vast core libraries, and determine the structure of your HTML for you. Both frameworks measure in the hundreds of kilobytes when packed and gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser — there's a lot of room underneath for libraries of a more moderate scope. Backbone is a 2 kilobyte include that provides just the core concepts of models, events, collections, views, and persistence.

Many of the examples that follow are runnable. Click the play button to execute them.

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.bind("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

bindobject.bind(event, callback)
Bind a callback function to an object. The callback will be invoked whenever the event (specified by an arbitrary string identifier) is fired. If you have a large number of different events on a page, the convention is to use colons to namespace them: "poll:start", or "change:selection"

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.bind("all", function(eventName) {
  object.trigger(eventName);
});

unbindobject.unbind([event], [callback])
Remove a previously-bound callback function from an object. If no callback is specified, all callbacks for the event will be removed. If no event is specified, all event callbacks on the object will be removed.

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

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

object.unbind();                    // Removes all callbacks on object.

triggerobject.trigger(event, [*args])
Trigger callbacks for the given event. Subsequent arguments to trigger will be passed along to the event callbacks.

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.bind('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

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

sidebar.promptColor();

extendBackbone.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() { ... },

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

  coordinates: function() { ... }

});

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.call(this, attributes, options);
    ...
  }
});

constructor / initializenew Model([attributes])
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"
});

getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")

setmodel.set(attributes, [options])
Set a hash of attributes (one or many) on the model. If any of the attributes change the models state, a "change" event will be fired, unless {silent: true} is passed as an option.

If the model has a validate method, it will be validated before the attributes are set, and no changes will occur if the validation fails.

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

unsetmodel.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.

idmodel.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.

cidmodel.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. Client ids take the form: c1, c2, c3 ...

attributesmodel.attributes
The attributes property is the internal hash containing the model's 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 toJSON instead.

toJSONmodel.toJSON()
Return a copy of the model's attributes for JSON stringification. This can be used for persistence, serialization, or for augmentation before being handed off to a view. The name of this method is a bit confusing, as it doesn't actually return a JSON string — 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));

savemodel.save(attributes, [options])
Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync. 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). Accepts success and error callbacks in the options hash, which are passed (model, response) as arguments.

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

Backbone.sync = function(method, model) {
  alert(method + ": " + JSON.stringify(model));
};

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

book.save();

destroymodel.destroy([options])
Destroys the model on the server by delegating an HTTP DELETE request to Backbone.sync. Accepts success and error callbacks in the options hash.

book.destroy({success: function(model, response) {
  ...
}});

validatemodel.validate(attributes)
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. validate is called before set and save, and is passed the attributes that are about to be updated. If the model and attributes are valid, don't return anything from validate; if the attributes are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically. set and save will not continue if validate returns an error. Failed validations trigger an "error" event.

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

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

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

one.set({
  start: 15,
  end:   10
});

urlmodel.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]/[id]".

A model with an id of 101, stored in a Backbone.Collection with a url of "/notes", would have this URL: "/notes/101"

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

isNewmodel.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.

changemodel.change()
Manually trigger the "change" event. If you've been passing {silent: true} to the set function in order to aggregate rapid changes to a model, you'll want to call model.change() when you're all finished.

hasChangedmodel.hasChanged([attribute])
Has the model changed since the last "change" event? If an attribute is passed, returns true if that specific attribute has changed.

book.bind("change", function() {
  if (book.hasChanged("title")) {
    ...
  }
});

changedAttributesmodel.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.

previousmodel.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.bind("change:name", function(model, name) {
  alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

previousAttributesmodel.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 callbacks to be notified when any model in the collection is changed, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods.

extendBackbone.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.

constructor / initializenew Collection([models], [options])
When creating a Collection, you may choose to pass in the initial array of models. The collection's comparator function may be included as an option. If you define an initialize function, it will be invoked when the collection is created.

var tabs = new TabSet([tab1, tab2, tab3]);

modelscollection.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.

Underscore Methods (24)
Backbone proxies to Underscore.js to provide 24 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…

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();
});

addcollection.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.

var Ship  = Backbone.Model;
var ships = new Backbone.Collection;

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

ships.add([
  new Ship({name: "Flying Dutchman"}),
  new Ship({name: "Black Pearl"})
]);

removecollection.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.

getcollection.get(id)
Get a model from a collection, specified by id.

var book = Library.get(110);

getByCidcollection.getByCid(cid)
Get a model from a collection, specified by client id. The client id is the .cid property of the model, automatically assigned whenever a model is created. Useful for models which have not yet been saved to the server, and do not yet have true ids.

atcollection.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.

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

comparatorcollection.comparator
By default there is no comparator function on a collection. If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in collection.models. Comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others.

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'));

sortcollection.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 function will maintain itself in proper sort order at all times. Triggers the collection's "refresh" event, unless silenced by passing {silent: true}

pluckcollection.pluck(attribute)
Pluck an attribute from each model in the collection. Equivalent to calling map, and returning a single attribute from the iterator.

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

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

alert(JSON.stringify(names));

urlcollection.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';
  }
});

refreshcollection.refresh(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 refresh to replace a collection with a new list of models (or attribute hashes), triggering a single "refresh" event at the end. Pass {silent: true} to suppress the "refresh" event.

fetchcollection.fetch([options])
Fetch the default set of models for this collection from the server, refreshing the collection when they arrive. The options hash takes success and error callbacks which will be passed (collection, response) as arguments. Delegates to Backbone.sync under the covers, for custom persistence strategies.

The server handler for fetch requests should return a JSON list of models, namespaced under "models": {"models": [...]} — additional information can be returned with the response under different keys.

Backbone.sync = function(method, model) {
  alert(method + ": " + model.url);
};

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

accounts.fetch();

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.

createcollection.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, your collection must have a model property, referencing the type of model that the collection contains.

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

var NYPL = new Library;

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

Backbone.sync

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

The method signature of Backbone.sync is sync(method, model, success, error)

When formulating server responses for Backbone.sync requests, model attributes will be sent up, serialized as JSON, under the model parameter. When returning a JSON response, send down the model's representation under the model key, and other keys can be used for additional out-of-band information. When responding to a "read" request from a collection, send down the array of model attribute hashes under the models key.

For example, a Rails handler responding to an "update" call from Backbone.sync would 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 JSON.parse params[:model]
  render :json => {:model => account}
end

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, it should look more like: model.bind('change', renderView) — and now everywhere that model data is displayed in the UI, it is always immediately up to date.

extendBackbone.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() {
    _.bindAll(this, "render");
  },

  render: function() {
    ...
  }

});

constructor / initializenew View([options])
When creating a new View, the options you pass 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, and tagName. If the view defines an initialize function, it will be called when the view is first created.

var doc = Documents.first();

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

elview.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, and id properties, if specified. If not, el is an empty div.

$ (jQuery)view.$(selector)
If jQuery is included on the page, each view has a $ or jQuery 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: $(selector, this.el)

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

renderview.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. You can use any flavor of JavaScript templating or DOM-building you prefer. Because Underscore.js is already on the page, _.template is already available. A good convention is to return this at the end of render to enable chained calls.

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

makeview.make(tagName, [attributes], [content])
Convenience function for creating a DOM element of the given type (tagName), with optional attributes and HTML content. Used internally to create the initial view.el.

var view = new Backbone.View;

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

$("#make-demo").append(el);

handleEventshandleEvents([events])
Uses jQuery's delegate 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"}. Omitting the selector causes the event to be bound to the view's root element (this.el).

Using handleEvents 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 handleEvents 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.render(this.model.toJSON()));
    this.handleEvents();
    return this;
  },

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

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

  ...

});

Change Log

0.1.1Oct 14, 2010
Added a convention for initialize functions to be called upon instance construction, if defined. Documentation tweaks.

0.1.0Oct 13, 2010
Initial Backbone release.


A DocumentCloud Project