A Gentle Intro To Backbone.js: Part 1
June 28, 2011
Backbone.js is a javascript framework which follows a MVC pattern (I couldn't find any better way to explain what it's). It makes your web application incredibly easy to maintain.
Model
Models are the fundamental structure of a Javascript application. Creating a model in Backbone is plain simple;
var Person = Backbone.Model.extend({ });
In order to create our own model, we need to extend Backbone.Model and define properties of our own model. You don't have to define initialize (but you'll when working in a real example) but if you define initialize, it'll be called when the model is created.
Getters And Setters
When we create a new instance of our model, we need to set some values.
Setters
var person = new Person({name: 'Milla Jovovich'}); // or var person = new Person(); person.set({name: 'Milla Jovovich'});
Getters
To get an attribute;
person.get('name');
You could check the documentation of Backbone to see the methods of models. For example; to create a JSON format of the model, we could simply do;
JSON.stringify(person);
Here's our Person model with some methods defined.
var Person = Backbone.Model.extend({ defaults: function() { 'name': 'Milla Jovovich', 'age': 36, }, changeName: function(name) { this.set({name: name}); }, clear: function() { this.destroy(); }, });
View
Views identify how your models look like. Backbone.js needs Underscore.js. Creating a view is simple;
var PersonView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render'); }, render: function() { this.el.html(_.template($('#some_html_container').html())); // or // this.el.html(_.template(this.model.toJSON())); return this; }, });
If the element we want to work on already defined in the DOM then;
var person_view = new PersonView({el: $('#container')});
Controller
Controllers define how our models interact. Backbone.Controller provides methods for routing. For example; application such as Twitter change the URL via #path (For example; http://twitter.com/#!/MillaJovovich). Here's a simple Controller example;
var PersonController = Backbone.Controller.extend({ routes: { 'about': 'about', 'search/:query': 'search', }, about: function() { alert('A Message'); } search: function(query) { this.doSearch(query); }, doSearch: function(query) { $.getJSON('/ajax/search?q='+e(query), function(data) { $('#result_container').html(data); }); } });
routes table is similar to Google App Engine's, Django's, or web.py's way of defining URLs. The above routes will match; http://domain/#about and http://domain/#search/milla.
As always, we need to create an instance;
var person_controller = new PersonController(); Backbone.history.start();
Backbone.history is a global router. It's mandatory to start it.
You may want to check out Thomas Davis' Backbone.js Tutorials website which you could find better explanations than this post.