I tried to understand the utility of backbone.js from its site http://documentcloud.github.com/backbone, but I still couldn\'t figure out much.
Can anybody help me b
Backbone.js is basically an uber-light framework that allows you to structure your Javascript code in an MVC (Model, View, Controller) fashion where...
Model is part of your code that retrieves and populates the data,
View is the HTML representation of this model (views change as models change, etc.)
and optional Controller that in this case allows you to save the state of your Javascript application via a hashbang URL, for example: http://twitter.com/#search?q=backbone.js
Some pros that I discovered with Backbone:
No more Javascript Spaghetti: code is organized and broken down into semantically meaningful .js files which are later combined using JAMMIT
No more jQuery.data(bla, bla)
: no need to store data in DOM, store data in models instead
event binding just works
extremely useful Underscore utility library
backbone.js code is well documented and a great read. Opened my eyes to a number of JS code techniques.
Cons:
Here is a set of great tutorials on using Backbone with Rails as the back-end:
CloudEdit: A Backbone.js Tutorial with Rails:
http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/
http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/
p.s. There is also this wonderful Collection class that lets you deal with collections of models and mimic nested models, but I don't want to confuse you from the start.
...a very small library of components which you can use to help organise your code. It comes packaged as a single JavaScript file. Excluding comments, it has less than 1000 lines of actual JavaScript. It's sensibly written and you can read the whole thing in a couple of hours.
It's a front-end library, you include it in your web page with a script tag. It only affects the browser, and says little about your server, except that it should ideally expose a restful API.
If you have an API, Backbone has a few helpful features that will help you talk to it, but you can use Backbone to add interactivity to any static HTML page.
...adding structure to JavaScript.
Because JavaScript doesn't enforce any particular patterns, JavaScript applications can become very messy very quickly. Anyone who has built something beyond trivial in JavaScript will have likely run up against questions such as:
Backbone seeks to answer these questions by giving you:
We call this an MV* pattern. Models, Views and optional extras.
Despite initial appearances, Backbone is fantastically light, it hardly does anything at all. What it does do is very helpful.
It gives you a set of little objects which you can create, and which can emit events and listen to each other. You might create a little object to represent a comment for example, and then a little commentView object to represent the display of the comment in a particular place in the browser.
You can tell the commentView to listen to the comment and redraw itself when the comment changes. Even if you have the same comment displayed in several places on your page all these views can listen to the same comment model and stay in sync.
This way of composing code helps to keep you from getting tangled even if your codebase becomes very large with many interactions.
When starting out, it's common to store your data either in a global variable, or in the DOM as data attributes. Both of these have issues. Global variables can conflict with each other, and are generally bad form. Data attributes stored in the DOM can only be strings, you will have to parse them in and out again. It's difficult to store things like arrays, dates or objects, and to parse your data in a structured form.
Data attributes look like this:
<p data-username="derek" data-age="42"></p>
Backbone solves this by providing a Model object to represent your data and associated methods. Say you have a todo list, you would have a model representing each item on that list.
When your model is updated, it fires an event. You might have a view tied to that particular object. The view listens for model change events and re-renders itself.
Backbone provides you with View objects that talk to the DOM. All functions that manipulate the DOM or listen for DOM events go here.
A View typically implements a render function which redraws the whole view, or possibly part of the view. There's no obligation to implement a render function, but it's a common convention.
Each view is bound to a particular part of the DOM, so you might have a searchFormView, that only listens to the search form, and a shoppingCartView, that only displays the shopping cart.
Views are typically also bound to specific Models or Collections. When the Model updates, it fires an event which the view listens to. The view might them call render to redraw itself.
Likewise, when you type into a form, your view can update a model object. Every other view listening to that model will then call its own render function.
This gives us a clean separation of concerns that keeps our code neat and tidy.
You can implement your render function in any way you see fit. You might just put some jQuery in here to update the DOM manually.
You might also compile a template and use that. A template is just a string with insertion points. You pass it to a compile function along with a JSON object and get back a compiled string which you can insert into your DOM.
You also have access to collections which store lists of models, so a todoCollection would be a list of todo models. When a collection gains or loses a model, changes its order, or a model in a collection updates, the whole collection fires an event.
A view can listen to a collection and update itself whenever the collection updates.
You could add sort and filter methods to your collection, and make it sort itself automatically for example.
As much as possible, application components are decoupled from each other. They communicate using events, so a shoppingCartView might listenTo a shoppingCart collection, and redraw itself when the cart is added to.
shoppingCartView.listenTo(shoppingCart, "add", shoppingCartView.render);
Of course, other objects might also be listening to the shoppingCart as well, and might do other things like update a total, or save the state in local storage.
Decoupling your objects like this and communicating using events means that you'll never get tangled in knots, and adding new components and behaviour is easy. Your new components just have to listen to the other objects already in the system.
Code written for Backbone follows a loose set of conventions. DOM code belongs in a View. Collection code belongs in a Collection. Business logic goes in a model. Another developer picking up your codebase will be able to hit the ground running.
Backbone is a lightweight library that lends structure to your code. Components are decoupled and communicate via events so you won't end up in a mess. You can extend your codebase easily, simply by creating a new object and having it listen to your existing objects appropriately. Your code will be cleaner, nicer, and more maintainable.
I liked Backbone so much that I wrote a little intro book about it. You can read it online here: http://nicholasjohnson.com/backbone-book/
I also broke the material down into a short online course, which you can find here: http://www.forwardadvance.com/course/backbone. You can complete the course in about a day.
I have to admit that all the "advantages" of MVC have never made my work easier, faster, or better. It just makes the whole codeing experience more abstract and time consuming. Maintenance is a nightmare when trying to debug someone elses conception of what separation means. Don't know how many of you people have ever tried to update a FLEX site that used Cairngorm as the MVC model but what should take 30 seconds to update can often take over 2 hours (hunting/tracing/debugging just to find a single event). MVC was and still is, for me, an "advantage" that you can stuff.