Introduction to Backbone.JS: Part 1


Let's dive into the world of Backbone.js.

Before moving into the basics of Backbone.js just have a look at the official definition of Backbone.js:

“Backbone.js gives structure to web 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 API over a RESTful JSON interface.”

Backbone.js is basically a light-weight JavaScript library that provides flexibility in web development. It adds an amount of functionality and structure to client-side code. It enforces the communication with the server using the RESTful API. Backbone.js is not a framework.

These libraries are used to create Single-Page Applications (SPAs).

In Backbone data is represented as Models that can be manipulated in various ways (including created, deleted, validated and saved to the server). It keeps front-end code modular and organized.

The attribute of a Model is changed after UI action, the Model triggers a changed event. Accordingly all the views will also be notified of the change. Simply put, when the model changes the views simply update themselves.

All the prototypes of Backbone.js are instantiated with the "new" keyword. There is an initialize() function that is called at the time of the instantiating of the prototypes of Backbone (Views, Models, Collections and Routers).

Backbone Structure: Backbone provides the various tools to introduce structure into client-side applications.

Modules of Backbone.JS

These are the following modules:

  • Views
  • Events
  • Models
  • Collections
  • Routers

Let us taste the basics of these modules.


If you have a basic knowledge of MVC, Views are just like "Controllers" in MVC. If you are unfamiliar with MVC frameworks then no worries. Here we will try to explain in a simple way.

A view's render() method can be bound to a model's change() event, enabling the view to instantly reflect model changes without requiring a full page refresh.

Backbone's Views

Takes user events (clicks, pressed keys, and so on) and perform accordingly.

Render HTML views and templates.

Interact with models that contain the data of the application.

  • Creating a View

    The View can be created by extending an existing view class of backbone. Here it is:
    1. var demoView = Backbone.View.extend({   });  
    The "el" property: It references the DOM object created in the brower. Every Backbone.js view has an "el" property.
    1. <div id="search_container"></div>   
    2.        <script type="text/javascript">  
    3.               SearchView = Backbone.View.extend({   
    4.                initialize: function(){   
    5.                    alert("function instantiated.");   
    6.                 }     
    7.  });      
    8.     var search_view = new SearchView({ el: $("#search_container")  
    9.        });  
    Every Backbone.js view has an “el” property, if we don't define the el property then Backbone.js constructs an empty div element as an "el" property.


Events are a module that can be mixed in to any object. Events provide the object the ability to bind and trigger custom named events. Events are not declared before they are bound. They may take arguments. For example:

  1. var object = {};  
  2.     _.extend(object, Backbone.Events);  
  3.     object.on("alert"function (msg) {   
  4.        alert("Triggered " + msg);    });  
  5.     object.trigger("alert""an event");  


Models are the heart of every application.

They contain the interactive data and the logic surrounding it, such as data validation, default values, data initialization, conversions and so on. 
  • Creating Backbone Model

    We need to extend the model class to create a backbone model. Here is how it is:
    1. var student = Backbone.Model.extend({  
    2. });  
  • How to instantiate a Model

    A Model can be instantiated using the "new" keyword.
    1. var student = new student();  
  • To Delete Model

    There is a destroy function in backbone.js to delete a model. This function can be used as follows:
    1. Student.destroy();  
    If the size of the method is slightly heavier then it takes time to delete the model. In this case we are not quite sure about the response, whether the method is called successfully or not.
    1. book.destroy({   
    2.        success: function () {  
    3.             alert("The model has been destroyed successfully");  
    4.         }   
    5.    });  
  • How to set the attributes in the model

    There are two ways to set attributes in the Model.

    • By ing a JavaScript object in the constructor.
      1. Student = Backbone.Model.extend({  
      2.         initialize: function () {   
      3.            alert("ing attributes");  
      4.         }   
      5.    });  
      6.    var student = new Student({ name: "Adam", sub: "science" });  
    • Using the model.set() method:
      1. Student = Backbone.Model.extend({
      2.         initialize: function () {
      3.             alert("By using SetMethod");
      4.         }
      5.     }); 
      6.    var person = new Person();
      7.  person.set({ name: "Adam", sub: "science" });  
  • Getting Attributes in a model

    To access model properties there is the model.get() method.
    1. Student = Backbone.Model.extend({ 
    2.        initialize: function () {
    3.             alert("Getting model attributes"); 
    4.        }  
    5.   }); 
    6.    var student = new Student({ name: "Rama", age: 20, sub: 'Maths' });
    7.     var age = student.get("age"); 
    8.    var name = student.get("name");
    9.     var sub = student.get("sub");  


Backbone collections are simply an ordered set of models such that it can be used in situations such as:

Model: Student, Collection: School
Model: Animal, Collection: Zoo

  • Creating a Backbone Collection

    Creating a backbone collection is similar to the backbone model. It is simply created by extending a Backbone.Collection as follows:
    1. var StudentCollection = Backbone.Collection.extend({    });  
  • Instantiating Collections

    Collections are also instantiated using the "new" keyword. We can create empty collections as well as Model objects to it.
    1. var collection1 = new StudentCollection(); //empty collection   
    2.  //ing Model as objects  
    3.  var book1 = new Book({ ID: 1, StudentName: "John" });
    4.  var book2 = new Book({ ID: 2, StudentName: "Adam" }); 
    5.  var collection2 = new StudentCollection([John, Adam]);  
    We can get and set Models in the collection, listen for events when an element in the collection changes and fetch the Model's data from the server.


Backbone routers are used for routing application URLs when using hash tags(#). It also enables us to use browser navigation with Single-Page Applications.

Actually routes facilitate the possibility of having deep copied URLs and history provides the possibility of using the browser navigation. A Router interprets anything after "#" tag in the URL.

Creating a backbone Router

Similar to various modules of backbone are JavaScript modules created by extending the Router class of backbone.

  1. var routers = Backbone.Router.extend({   
  2.     routes: { 
  3.     },help: function() { 
  4.     ... },  
  5.     search: function(query, page)
  6.     { ... } });  

Backbone.History: It handles hashchange events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.

The Backbone.history.start() method will simply tell Backbone that it's okay to begin monitoring all hashchange events.


During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.

Backbone.js code sample

Here I am trying to present a simple code sample in which I will be using nearly all the modules of Backbone.js like View, Collection, Model and Events.

In this example I am using the 3 JavaScript Libraries Backbone.js, jQuery, Underscore.js.

We need to create a HTML file for front view and add JavaScript code to it.

  2. <!DOCTYPE html >  
  3. <html>  
  4. <head>  
  5.     <title>Backbone.js By Shridhar</title>  
  6.     <script type="text/javascript"   
  7.       src=""></script>  
  8.     <script type="text/javascript"   
  9.       src=""></script>  
  10.     <script type="text/javascript"   
  11.       src=""></script>  
  12.     <script type="text/javascript"   
  13.       src="sampleTask.js"></script>  
  14. </head>  
  15. <body>  
  16.     <input type="text"  id="txtinput" placeholder="Add items" />  
  17.     <button id="input">Click to Add</button>  
  18.     <ul id="itemslist"></ul>  
  19.     <script type="text/javascript">  
  21.         $(function() {  
  23.            ItemList = Backbone.Collection.extend({ // creating collection  
  24.                 initialize: function() {  
  25.                 }  
  26.             });  
  28.             ItemView = Backbone.View.extend({ // creating view  
  30.                 tagname: 'li',  
  31.                 events: {                                
  32.                     'click #input''getitems'  
  33.                 },  
  35.                 initialize: function() {  
  36.                     var thisView = this;  
  37.                     this.itemlist = new ItemList;  
  38.                     _.bindAll(this'render');  
  39.                     this.itemlist.bind("add"function(model) {  
  40.                         thisView.render(model);  
  41.                     })  
  42.                 },  
  44.                 getTask: function() {  
  45.                     var task_name = $('#txtinput').val();  
  46.                     this.itemlist.add({ name: task_name });  
  47.                 },  
  49.                 render: function(model) {  
  50.                     $("#itemslist").append("<li>" +   
  51.                        model.get("name") + "</li>");  
  52.                     console.log('rendered')  
  53.                 }  
  55.             });  
  57.             var view = new ItemView({ el: 'body' });  
  58.         });  
  62.     </script>  
  63. </body>  
  64. </html>  

Add some items:

Items will appear in the list after the Click event, in other words after clicking “Click to Add”.

How the preceding code works

In the preceding code, we are trying to add the value in the collection in the HTML list element. Initially we created a collection by extending Backbone. For the collection, similarly we create a view that takes user events (clicks, pressed keys and so on) and performs accordingly. After a "click" event occurs, the getitems method will be called that will get the values from the input type we use. After getting the items from the input types, items will be added to the Itemlist. The collection.render() method is responsible for displaying that collection in the HTML element, for that purpose we had to use a list element.

Model in Backbone.JS : Part 2  >>

Similar Articles