Getting Started with Backbone.js
Tutorial Details
- Topic: JavaScript
- Difficulty: Medium
- Estimated Completion Time: 1 hour
Unlike its web development peers, JavaScript has never really had much in the way of frameworks to provide structure. Thankfully, in recent years, that’s beginning to change.
Today, I’d like to introduce you to Backbone.JS, a sweet little library that makes the process of creating complex, interactive and data driven apps so much easier. It provides a clean way to surgically separate your data from your presentation.
Overview of Backbone.JS
Created by Jeremy Ashkenas, the JS ninja who built CoffeeScript, Backbone is a super light-weight library that lets you create easy to maintain front ends. It’s backend agnostic and works well with any of the modern JavaScript libraries you’re already using.
Backbone is a collection of cohesive objects, weighing in at a shade under 4kb, that lend structure to your code and basically helps you build a proper MVC app in the browser. The official site describes its purpose as so:
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.
Let’s face it: the above is a little hard to parse and make sense of. So let’s go ahead and deconstruct the jargon a bit, with help from Jeremy.
Key-value binding and custom events
When a model’s contents or state is changed, other objects that have subscribed to the model are notified so they can proceed accordingly. Here, the views listen to changes in the model, and update themselves accordingly instead of the model having to deal with the views manually.
Rich API of enumerable functions
Backbone ships with a number of very useful functions for handling and working with your data. Unlike other implementation, arrays in JavaScript are pretty neutered, which really is a hampering problem when you have to deal with data.
Views with declarative event handling
Your days of writing spaghetti bind calls are over. You can programmatically declare which callback needs to be associated with specific elements.
RESTful JSON interface
Even though the default method is to use a standard AJAX call when you want to talk to the server, you can easily switch it out to anything you need. A number of adapters have sprung up covering most of the favorites including Websockets and local storage.
To break it down into even simpler terms:
Backbone provides a clean way to surgically separate your data from your presentation. The model that works with the data is only concerned with synchronizing with a server while the view’s primary duty is listening to changes to the subscribed model and rendering the HTML.
A Quick FAQ
I’m guessing you’re probably a little fazed at this point, so let’s clear a few things up:
Does it replace jQuery?
No. They’re pretty complementary in their scopes with almost no overlaps in functionality. Backbone handles all the higher level abstractions, while jQuery – or similar libraries – work with the DOM, normalize events and so on.
Their scopes and use cases are pretty different and because you know one doesn’t mean that you shouldn’t learn the other. As a JavaScript developer, you should know how to effectively work with both.
Why should I be using this?
Because more often than not, the front end code devolves into a steaming, dirty pile of nested callbacks, DOM manipulations, HTML for the presentation amidst other unsayable acts.
Backbone offers a significantly clean and elegant way of managing this chaos.
Where should I be using this?
Backbone is ideally suited for creating front end heavy, data driven applications. Think the GMail interface, new Twitter or any other revelation of the past few years. It makes creating complex apps easier.
While you can shoehorn it for more mainstream web pages, this is really a library that is tailored for web apps.
Is it similar to Cappuccino or Sproutcore?
Yes and no.
Yes, because like the above mentioned frameworks, this is primarily intended for creating complex front ends for web applications.
It’s dissimilar in that Backbone is quite lean, and ships with none of the widget that the others ship with.
Backbone is incredibly light weight, at under 4kb.
There’s also the fact that Cappuccino forces you to write your code in Objective-J, while Sproutcore’s views have to be declared programmatically in JS. While none of those approaches are wrong, with Backbone, normal JavaScript is harnessed by your run of the mill HTML and CSS to get things done, leading to a gentler learning curve.
I can still use other libraries on the page, right?
Absolutely. Not only your typical DOM accessing, AJAX wrapping kind, but also the rest of your templating and script loading kind. It’s very, very loosely coupled, which means you can use almost all of your tools in conjunction with Backbone.
Will it usher in world peace?
No, sorry. But here’s something to cheer you up.
Ok, now with that out of the way, let’s dive in!
Getting to Know Backbone’s Backbone
The MVC in Backbone originally stood for Models, Views and Collections, since there were no controllers in the framework. This has since changed.
Backbone’s core consists of four major classes:
- Model
- Collection
- View
- Controller
Since we’re a little strapped for time, let’s take a look at just the core classes today. We’re going to do a follow up tut with a super simple app to demonstrate the concepts taught here since it’d be too much to put everything in a single article and expect the reader to parse everything.
Keep your eyes peeled over the next couple of weeks!
Model
Models can mean different things in different implementations of MVC. In Backbone, a model represents a singular entity — a record in a database if you will. But there are no hard and fast rules here. From the Backbone website:
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.
The model merely gives you a way to read and write arbitrary properties or attributes on a data set. With that in mind, the single liner below is completely functional:
var Game = Backbone.Model.extend({});
Let’s build on this a bit.
var Game = Backbone.Model.extend({
initialize: function(){
alert("Oh hey! ");
},
defaults: {
name: 'Default title',
releaseDate: 2011,
}
});
initialize will be fired when an object is instantiated. Here, I’m merely alerting out inanities — in your app you should probably be bootstrapping your data or performing other housekeeping. I’m also defining a bunch of defaults, in case no data is passed.
Let’s take a look at how to read and write attributes. But first, let’s create a new instance.
// Create a new game
var portal = new Game({ name: "Portal 2", releaseDate: 2011});
// release will hold the releaseDate value -- 2011 here
var release = portal.get('releaseDate');
// Changes the name attribute
portal.set({ name: "Portal 2 by Valve"});
If you noticed the get/set mutators, have a cookie! A model’s attributes can’t be read through your typical object.attribute format. You’ll have to go through the getter/setter since there’s a lower chance of you changing data by mistake.
At this point, all the changes are only kept in memory. Let’s make these changes permanent by talking to the server.
portal.save();
That’s it. Were you expecting more? The one-liner above will now send a request to your server. Keep in mind that the type of request will change intelligently. Since this is a fresh object, POST will be used. Otherwise, PUT is used.
There are a lot more features, Backbone models give you by default but this should definitely get you started. Hit the documentation for more information.
Collection
Collections in Backbone are essentially just a collection of models. Going with our database analogy from earlier, collections are the results of a query where the results consists of a number of records [models]. You can define a collection like so:
var GamesCollection = Backbone.Collection.extend({
model : Game,
}
});
The first thing to make note of is that we’re defining which model this is a collection of. Expanding on our example earlier, I’m making this collection a collection of games.
Now you can go ahead and play around with your data to your hearts contents. For example, let’s extend the collection to add a method that returns only specific games.
var GamesCollection = Backbone.Collection.extend({
model : Game,
old : function() {
return this.filter(function(game) {
return game.get('releaseDate') < 2009;
});
}
}
});
That was easy, wasn’t it? We merely check if a game was released before 2009 and if so, return the game.
You can also directly manipulate the contents of a collection like so:
var games = new GamesCollection games.get(0);
The above snippet instantiates a new collection and then retrieves the model with an ID of 0. You can find an element at a specific position through referencing the index to the at method like so: games.at(0);
And finally, you can dynamically populate your collection like so:
var GamesCollection = Backbone.Collection.extend({
model : Game,
url: '/games'
}
});
var games = new GamesCollection
games.fetch();
We’re merely letting Backbone where to get the data from through the url property. With that done, we’re merely creating a new object and calling the fetch method which fires of an asynchronous call to the server and populates the collection with the results.
That should cover the basics of collections with Backbone. As I mentioned, there are tons of goodies here what with Backbone aliasing a lot of nifty utilities from the Underscore library. A quick read through of the official documentation should get you started.
View
Views in Backbone can be slightly confusing at first glance. To MVC purists, they resemble a controller rather than a view itself.
A view handles two duties fundamentally:
- Listen to events thrown by the DOM and models/collections.
- Represent the application’s state and data model to the user.
Let’s go ahead and create a very simple view.
GameView= Backbone.View.extend({
tagName : "div",
className: "game",
render : function() {
// code for rendering the HTML for the view
}
});
Fairly simple if you’ve been following this tutorial so far. I’m merely specifying which HTML element should be used to wrap the view through the tagName attribute as well as the ID for it through className.
Let’s move ahead to the rendering portion.
render : function() {
this.el.innerHTML = this.model.get('name');
//Or the jQuery way
$(this.el).html(this.model.get('name'));
}
el refers to the DOM element referenced by the view. We’re simply accessing the game’s name to the element’s innerHTML property. To put it simply, the div element now contains the name of our game. Obviously, the jQuery way is simpler if you’ve used the library before.
With more complicated layouts, dealing with HTML within JavaScript is not only tedious but also foolhardy. In these scenarios, templating is the way to go.
Backbone ships with a minimal templating solution courtesy of Underscore.JS but you’re more than welcome to use any of the excellent templating solutions available.
Finally, let’s take a look at how views listen to events. DOM events first.
events: {
'click .name': 'handleClick'
},
handleClick: function(){
alert('In the name of science... you monster');
// Other actions as necessary
}
Should be simple enough if you’ve worked with events before. We’re basically defining and hooking up events through the events object. As you can see above, the first part refers to the event, the next specifies the triggering elements while the last part refers to the function that should be fired.
And now onto binding to models and collections. I’ll cover binding to models here.
GameView= Backbone.View.extend({
initialize: function (args) {
_.bindAll(this, 'changeName');
this.model.bind('change:name', this.changeName);
},
});
The first thing to note is how we’re placing the binding code in the initialize functions. Naturally, it’s best to do this from the get go.
bindAll is a utility provided by Underscore that persists the value of a function’s this value. This is specially useful since we’re passing a bunch of functions around and functions specified as callbacks have this value erased.
Now whenever a model’s name attribute is changed, the changeName function is called. You can also make use of the add and remove verbs to poll for changes.
Listening to changes in a collections is as simple as replacing model with collection while binding the handler to the callback.
Controller
Controllers in Backbone essentially let you create bookmarkable, stateful apps by using hashbangs.
var Hashbangs = Backbone.Controller.extend({
routes: {
"!/": "root",
"!/games": "games",
},
root: function() {
// Prep the home page and render stuff
},
games: function() {
// Re-render views to show a collection of books
},
});
This is very familiar to routing in traditional serverside MVC frameworks. For example, !/games will map to the games function while the URL in the browser itself will be domain/#!/games.
Through intelligent use of hashbangs, you can create apps that are heavily JS based but also bookmarkable.
If you’re worried about breaking the back button, Backbone has you covered too.
// Init the controller like so var ApplicationController = new Controller; Backbone.history.start();
With the above snippet, Backbone can monitor your hashbangs and in conjunction with the routes you’ve specified earlier, make your app bookmarkable.
What I Learned from Backbone
Overall, here are some lessons I learned from the Backbone way of creating applications:
- We really need MVC for the front end. Traditional methods leave us with code that’s too coupled, messy and incredibly hard to maintain.
- Storing data and state in the DOM is a bad idea. This started making more sense after creating apps that needed different parts of the app to be updated with the same data.
- Fat models and skinny controllers are the way to go. Workflow is simplified when business logic is taken care of by models.
- Templating is an absolute necessity. Putting HTML inside your JavaScript gives you bad karma.
It’s sufficient to say that Backbone has caused a paradigm shift in how front ends should be constructed, at least for me. Given the very broad scope of today’s article, I’m sure you have a ton of questions. Hit the comments section below to chime in. Thank you so much for reading and expect a ton more Backbone tutorials in the future!

finally great to see, mvc in js. nice post. This will be a great help in game development.
pretty Good Read Siddarth, thank you.
might consider using Backbone.js in my future projects.
Are you planning on also reviewing Javascript MVC?
What do you think?, Which one is better?
Sure, in the near future we’ll cover JavaScript MVC.
Personally, I like Backbone since it’s a lot more leaner and less restrictive.
thanks for replying
FYI, you’re comparing ‘price’ to 2009, and not ‘releaseDate’ in your filtering example for models. Otherwise, this was a fantastic article! Thanks for introducing me to my new Javascript toy. :D
Whoops! Fixed, thanks!
hope to see more tuts for backbone.js
Looking forward to more in depth tutorials on this. Especially focused on single page web apps that I can deploy with Phonegap!
Same here! Did you find any other tutorial in the meantime?
This is just what I needed for my next front end heavy web app :)
Great write up thanks for touching on the main points.
Do you have a quick sample app you can post from your game demo so we can get the full effect?
Hey Andrew,
We’re going to do a follow up tut with a super simple app to demonstrate the concepts taught here. I thought it’d be too much to put everything in a single article and expect the reader to parse everything.
Keep your eyes peeled over the next couple of weeks!
Thanks for reading!
thanks! :) finally backbone.js on Nettuts :) i hope there will be more tuts like that :)
I’ve been waiting for this day for ages: http://nodebeginner.org/ and this article out in one day. nice!
This is fantastic, I’ve always held off on fully learning js because of it’s difficulties and lack of mvc support. Maybe now with backbone this will change!
Try spine.js its even more “lean”
nettuts: i love you!
why? because you guys actually DO tutorials, your readers request on fb :-)
btw: if you like backbone.js, check out brunchwithcoffee.com.
its a small client-side framework that combines backbone with coffeescript, eco, stylus and stitch
So, is backbone.js essentially bringing class structure to javascript? If so, isn’t that a backwards step? Javascripts prototypes are more powerful according to Douglas Crockford. Can the same thing be accomplished by using a separate language like php to talk to the server and send information back to the javascript?
In terms of creating a de facto standard for AJAX applications I agree with you, however, every problem has a solution and I think that this framework solves at least one.
I have been recently charged with creating an application that is autonomous from it’s datasource and backend architecture, implemented using asynchronous javascript. I believe that backbone.js solves this problem quite well.
As long as we don’t take any one way as gospel I think any ideas are welcome.
Great to see more coverage of Backbone.js. I just started working with it and like it a lot, but it was a total rewrite of our current client stuff (which was a JavaScript mess).
Would love to see how people would combine Backbone.js with a HTML5 canvas drawing (multiple model-types and objects in the same one) in the mix. Maybe a future article?
Backbone seems very tied to the DOM and I have had to hack my own way through, but I am guessing my way isn’t that great…
Don’t worry, we’ll do a follow up with a simple app to demonstrate the features on show here. Probably more than one app since you can take a number of approaches with Backbone.
Thanks for reading!
I’d love to see that simple app follow-up article. Is it published elsewhere by chance?
Hi Siddharth, I was just wondering if you could provide me with the url of the follow-up? Thanks a lot.
Great intro article, unlike many others where the author is speaking in hardcore JS language and fails to explain the fundamental concepts.
Would also be nice with a full walkthrough of creating an app. Many articles on Backbone leave that stuff out and you end up with an incomplete picture of the framework.
Nice tutorial, Siddharth.
Keep posting such nice articles.
More of this please…soon!!!
Great tutorial, thank you.
Looks good, but still wondering what advantages it would give me when creating a new dashboard for future webshops and improving/rebuilding the CMS.
Ohyeah… one of the samples has a little typo… releaseData should be releaseDate .
Is it compatible with all browsers.
I really like the look of this, but it seems like it is more of an implementation of the publisher/subscriber pattern than MVC really.
I have been playing around with Backbone.js for a while now. This article is an excellent start. Backbone.js is just amazing, as it give you structure to your application code, you can have X Views for 1 Model, and so on… The sync() method is also very smart : override it and you can use localStorage, HTML5 SQLite database, or even just an XML document. Clearly the JS framework of 2011 in my point of view.
And, yes, it is a MVC framework,don’t be fooled by some comments… ;)
I have been playing around with Backbone.js for a while now. This article is an excellent start. Backbone.js is just amazing, as it give you structure to your application code, you can have X Views for 1 Model, and so on… The sync() method is also very smart : override it and you can use localStorage, HTML5 SQLite database, or even just an XML document. Clearly the JS framework of 2011 in my point of view.
And, yes, it is a MVC framework,don’t be fooled by some comments… ;)
I use Backbone.js, I like it, but it has its limitations.
Backbone has two limitations that I’ve learned to “work around”: the first is that highly complex data sets are not well-served by Backbone. Writing a deeply RESTful application where your models are complex object sets can lead to some developer confusion, as the first tier of references will be accessed via Backbone’s get()/set() methods, but deeper accesses will be accessed via javascript’s dot notation.
This can also lead to the dangers of assuming that a get() returns a copy of the object. It returns a copy of the first tier, but those are copies of references– if you change a value in an inner tier, you’re changing the model explicitly. The Backbone.js toJSON() method also returns a shallow copy: changing inner data of an object in toJSON will result in mangling the parent model.
This can make passing JSONified objects to a templater difficult; often, you want to do client-side preprocessing of information to be displayed (dates, numbers, and percentages humanized, for example), and decorating the object to be passed to the template can be fraught with these kinds of issues.
The other limitation is that the objects created with Backbone Views have concrete lifecycles that can make integrating them with jQuery’s delegate() or bind() fail. For creating large lists of complex objects, I’ve fallen back to decomposing my view to manage the frame and frame-level events, and creating standard Javascript objects controlled with jQuery’s live() method to manage individual object displays.
All in all, I find Backbone a very useful tool, but it is just a tool. Using it in a very large project can help organize your code in elegant ways. If your datasets are straightforward, using it both on the client side and the server side (with node.js) is awesome, and a socket.io hub at both ends can make writing an interactive experience a breeze.
In reply to your first limitation, I saw that right off the bat. This is definitely a limitation when using Backbone especially for when you are writing an app completely in JavaScript. That being said, this would be a fairly easy change to the Backbone API using a hasOne/hasMany paradigm. This would then in effect be recursive.
This is not to say that if you are controlling the back-end that you should not also be using and validating the data with your own back-end domain models.
I wonder if you could use the set/get events to trigger the hydration of an model rather than using the default behavior.
You should highlight the power of underscore.js as well. Backbone.js is written on top of underscore.js, a toolkit of awesome power that allows you to do binding, functional programming, chaining, and other common modern programming idioms without having to haul in a huge library. I’ve seen people use jQuery for their DOM manipulation, but pull in Protoype *and* YUI for “that one thing those do better.” Underscore might just be the small, powerful kit that has “that one thing” without having to drag all of those Starship Enterprise-sized libraries along with them.
Excellent tutorial. I’m really working on improving my javascript skills. I think this may be the route I want to go. Cheers.
Great! Loved it!!
Brill just what i needed. I have a nest of javascript that needs tidying.
Are the source files for this tutorial actually available in the premium members area? If so, I haven’t been able to locate them. A few piece of information are missing here. Perhaps they’ll be covered in the follow up.
– Attaching a game to a game collection
– Switching between routes
– Having multiple views that may or may not have DOM already on the page
Great info. Excited to see more advanced coverage of Backbone. Thanks.
I really need to start brushing up my javascript skills but I never know where to start and there seems to always be new things to learn
It is a very nice backbone app on substance.io – check it out !
It’s frustrating that the code in this tutorial isn’t actually complete enough to run. Something simple is missing, but I can’t figure out what. For example: what actually creates new GameView views and sticks them to the DOM? Could someone here convert this to a simple running example and post the code somewhere?
I am stuck here, too.
Also, there are a few minor glitches in here (like superflous commas, or a reference to “book” where it clearly should read “game”).
It is still a decent introduction to the topic, but it seems to be a little “unpolished”.
Thanks, though!
I am working on a community based resource for Backbone.js tutorials.
Anyone looking for more beginner tutorials can visit;
http://backbonetutorials.com
A decent overview but not mentioning anything about the need to use underscore.js makes this tutorial flawed. I like Thomas Davis’s site much, much better.
How do I handle the PUT requests using PHP?
I have the same question, cannot seem to find any information on the web to help.
Just check the value of $_SERVER['REQUEST_METHOD'], it will be “PUT” if it is a PUT request.
This is great for Javascript-driven web applications, but I wouldn’t use it for websites which have to work without Javascript, and be crawlable by Google.
(For those websites, I generally prefer a progressive enhancement approach, with my custom Javascript logic encapsulated by jQuery plugins, which are executed on page load by a boot-strapper.)
But this framework would be great for games, mobile apps, and anything else that’s highly interactive, and doesn’t require a semantic-HTML approach.
Hei, when next episode ? it’s been 2 months :)
Nice introduction to Backbone. You have an extra closing bracket “}” on your collections examples that throw parse errors!
Nice Post. . .
It would be great if someone give more example site and also any body has developed a UI from Backbone.js, i am new to this.
Thanks for the tutorial, but you guys at tutsplus.com should consider proofreading… I am about a quarter of the way through and am questioning the legitimacy of tutsplus.com because this article is already filled with all kinda of obvious grammatical mistakes… missing words and so on.
best backbone tutorial i’ve seen so far – Thanks :)
Here, you go, working code for the tutorial: http://jsfiddle.net/jkulak/xrqpN/
Additional resources (jQuery and underscore.js) are used.
I added steps that were missing in the tutorial.
I just wanted to add that Sproutcore no longer requires you to write views in Javascript. You can write views with Mustache templates (HTML).
Backbone seems decent, and clearly some very smart people like it, but from what I’ve seen it seems so much less declarative and intuitive that the MVVM approach uses by KnockoutJS.
Did the follow-up tutorial ever come out?
Nice intro to Backbone.js, a more indepth version or followup is essential — as this library will undoubtedly be playing a big part in web applications in the future.
Also, it would be worth updating this to work with version 0.5.0+ (ie: using Router instead of Controller).
Great job on the tutorial Siddharth! Matt: if you are interested, I just wrote a three part tutorial including CRUD coverage here: http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/
Thanks for the overview … I couldn’t agree more with the “lessons learned” summary. Apart from one thing, twas ever so. I/we put my/our first [commercial] on-line (client-server) solution ‘out there’ in around 1981.
At that time:
* We really need(-ed) MVC for the front end — Smart host-located rendering or smart cluster controllers
* Storing data and state in the DOM is a bad idea — A client-state or user-state properties per terminal or user (and both).
* Fat models and skinny controllers are the way to go — May be: I’d say the “logic” needs to be in the right layer or level. It give you several medium size models that add-to a ‘fat model’.
* Templating is an absolute necessity — For me, it was a great loss to ICT when the ‘industry’ left that one behind. Good to see it making a come-back.
It’s really possible few remember on-line processing before the 90-s (internet got big after WWW about 1996…). I won’t mind reactionary responses to this comment, we need them. Unfortunately those responses will come from folk believing or looking for short-cuts that probably don’t exist. I remember Brady Booch saying at a talk way back in that pre-1996 era: “You can’t remove complexity”.
w.
Hey Siddharth,
In the view tutorial, where you’re defining the event handling:
“click .name : handleClick”
is ‘.name’ meant to be ‘.game’ to match the className defined in the previous step? Or is it referring to the attribute of the model.
Thanks,
Jason
in backbonejs 0.9.1, there is no Controller, it renamed to Backbone.Router
Great tutorial! Giving me a good overview of backbone.js!
Recognized some code failures:
At the view section: “var Gameview” instead of “Gameview”.
At the collection section: There is a obsolete curly bracket at row eight.
At the models section: I’m new to backbone.js, so sorry for false information, but models can’t be initialized? At least it doesn’t worked for me.
Keep on! :-)