Print Shortlink

Modularize JavaScript with Backbone

The jQuery code that I have used in projects have always had modularity issues. The code looks clumsy and messy making it very difficult to maintain. My work with Ext JS4 and Sencha Touch made me looking for a MVC implementation with jQuery code. I landed up with Backbone.

Backbone is a JavaScript library that provides an excellent facility to modularize the client-side JavaScript code. It provides a solution to implement MVC pattern. You can modularize the code by creating models and views resulting in highly reusable code.

I have a very simple application implemented where I display a list of countries in a ul tag using jQuery. I wrap up this whole exercise using Backbone.

To begin with you need to have the scripts Backbone.js, jquery.js and a dependency library UnderScore.js included in my file as shown below.

 <script src="jquery-1.6.1.js"></script>
 <script src="underscore-min.js"></script>
 <script src="backbone-min.js"></script>

I define a Model class called Country and a collection of Models called ‘Countries’. I use the Backbone.Model.extend and Backbone.Collection.extend syntax as shown below.

var Country = Backbone.Model.extend({
	defaults : {
			name : "--",
			capital : "--"
var Countries = Backbone.Collection.extend({
	model : "country"
var countriesInAsia = new Countries([
	  new Country({name:"India",capital:"New Delhi"}),
	  new Country({name:"SriLanka",capital:"Colombo"}),
	  new Country({name:"Japan",capital:"Tokyo"})

Let’s display the countriesInAsia in an unordered list using jQuery. You can define a view class using Backbone.View.extend syntax. This class has an initialize and render method that renders the countriesInAsia in an UL tag. The UL tag is rendered inside the body element. Backbone view holds the container inside which you want to render the UI in an “el” element. In this case “el” is the body element. The code is shown below.

  var CountryView = Backbone.View.extend({   
        el : $("body"),		
        initialize: function(){
	render: function(){
      	     $(this.el).append("<ul id='countries'></ul>");
		$("ul#countries").append("<li>" +"name") + "</li>");
	changeColorToRed : function(event){
	changeColorToWhite : function(event){
       events : {
		"mouseover li" : "changeColorToRed",
		"mouseout li" : "changeColorToWhite"
  var countryView = new CountryView();

What’s amazing is the event handling facility. The events property just lists down the possible events and their listeners. It cannot get better than this.
One of the finest frameworks to write highly maintainable JavaScript(particulary jQuery) code. I am planning to write few more posts on this framework.

Page 1 of 1

One Response

  1. GuessingGame with Backbone.js

    […] implement this game using Backbone.js. In my earlier post on Backbone I had discussed the basics of model, collection and view. We’ll use them to implement the […]

Leave a Reply