Introduction to Backbone.js

Backbone.js is a JavaScript framework that attempts to structure a web application by separating the business logic from the user interface. Backbone.js defines special objects called Model which manages business logic and domain data, the UI related activities are managed by object called View.


Model

The model is a special object in backbone which manages the business data and the business logic. It is responsible for loading and saving model data from the server by integrating with RESTful API. The model is expected to be designed in such a way that is contains all functions required for manipulation of business data. It is supposed to be atomic and should not involve in any UI related activities. To create a model object we should extend the Backbone.Model as shown below:

var myModel = Backbone.Model.extend({
    ...
});

View

View is a special object in backbone.js which manages the user interface. It is responsible for rendering the user interface and capturing the user inputs, passing it on to the models. It can listen to updates in the model data and re-render the user interface accordingly. It should be designed as an atomic unit and should not involve in any processing of the model data. To create a model object we should extend the Backbone.View as shown below:

var myView = Backbone.View.extend({
    ...
});

Sample Example

The example below displays the temperature of each day from 1st March to 31st March. The model data changes every 2 seconds, and the view listens to this change and updates the UI with the updated date and temperature.

Model:

Our model is quite simple, it has 2 attributes, date and temperature. We had set the default value of the attributes using the 'defaults' function of Backbone.Model. It has two functions updateValue() and update(). The updateValue() function updates the date and temperature and the update() function calls update value every 2 seconds.

var TemperatureModel = Backbone.Model.extend({
    defaults : {
        date : "1 March 2015",
        temperature : 27
    },
    
    updateValue: function(){
        var currDate = this.get('date');
        var day = currDate.substring(0, 2);
        var newDay;
        if(day == '31')
            newDay = 1;
        else
            newDay = parseInt(day) + 1;
        
        this.set({
            'date' : newDay + " " +currDate.substring(2), 
            'temperature': Math.floor(Math.random() * 45) + 15
        });    
    },
    
    update: function(){
        var self = this;
        setInterval(function() {self.updateValue()}, 2000);
    }
});

View:

The view detects to any update on the model and renders the html with the updated model attributes. We had asked the view to listen to the model update in the initialize function. This is a Backbone.View function which is called when the constructor is invoked. It is used to perform any task on object creation.

var TemperatureView = Backbone.View.extend({
    
    initialize: function(){
        this.render();
        this.listenTo(this.model, 'change', this.render); <!-- Call render on model update -->
    },
    
    render: function(){
          document.getElementById("container").innerHTML = 
          "Temp on "+this.model.get('date') + " is " + 
          this.model.get('temperature') +"°C";
    }
});

HTML Page:

Here we import the required javascript files jquery.min.js, underscore.js(required by backbone) and backbone.js. We had created the object of our model and view and called the model's update method to update the date and temperature.

Notice that the view is provided with the model it should work on.

<!DOCTYPE HTML>
<html>
<head>
	<title>Backbone js Intro</title>
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/underscore.js"></script>
	<script type="text/javascript" src="js/backbone.js"></script>
	<script type="text/javascript" src="js/intro.js"></script> <!-- Contains the model and view -->
	<script type="text/javascript">
		var model = null;
		var view = null;

		$(document).ready(function(){
			model = new TemperatureModel();
			view = new TemperatureView({model:model});
			model.update();
		});
	</script>
</head>
<body>
	<div id="container"></div>
</body>
</html>

Result

RELATED ARTICLES

Introducing Backbone Collection

Backbone Collections are set of related models. This is used in situations where we are handling a set of related models.

View Article

Understanding Model and View in Backbone.js

Model and View are special objects that form an integral part of Backbone.js. These are used to keep the data and the business logic separate from the user interface.

View Article