BackboneJS has a hard dependency on Underscore.js and a soft dependency on Jquery. So, the following components are required to start working with BackboneJS:
- Backbone.js
- Underscore.js (>=1.4.3)
- Jquery (>=1.7.0)
So, after having all these prerequisites we will test if it has been set up properly by writing our first BackboneJSDemo.html file such as below:
<html> <head> <meta charset="utf-8"> <title>BackboneJS Tutorial</title> </head> <body> <script src="underscore.js"></script> <script src="jquery.js"></script> <script src="backbone.js"></script> <body> <html>
Understanding BackboneJS
Like many other libraries, Backbone is also one of the most prominent JavaScript libraries. It provides proper structuring to web applications with its most robust components. BackboneJS is gaining special attention due to the following attributes:
- It is simple and easy to use
- It is a light weight framework
- It is of object oriented Nature
- It provides structure to JavaScript that makes it easy to understand
Major Components of BackboneJS:
BackboneJS consists of different components that we will be discussing in detail below. The major components of BackboneJS are:
- Views
- Events
- Models
- Collections
- Routers
BackboneJS Views:
BackboneJS Views are used to reflect how our application model data will look like. They are also used to listen for different types on events based upon JavaScript selectors and act accordingly based upon the type of event fired. The sample code below describes how we can use views to render application’s model data:
var BackbonejsView= Backbone.View.extend({ el: $('body'), // attaches `this.el` to an existing element. //The initialize function is always called when instantiating a Backbone View. initialize: function(){ _.bindAll(this, 'render'); // every function that uses 'this' as the current object should be in here this.render(); }, render: function(){ $(this.el).append("<ul> <li>Welcome to backboneJS JavaScript Library</li> </ul>"); } }); //Instantiating Application View var listView = new BackbonejsView(); So, the above example simply shows that how the BackboneJS Views are used. For more details regarding BackboneJS Views please refer: BackboneJS Views in Detail
BackboneJS Models:
Models are the heart of any JavaScript application. BackboneJS Model is basically a Java Script object, i.e. key-value pairs used to represent our application data which can be created, validated with respect to specified constraints, saved to the server and destroyed. Models provide basic set of functionality to handle event triggering, persistence, etc. The following example elaborates on how we can use models in our application:
var Employee = Backbone.Model.extend({ defaults: { name: 'John', address: 'Street 5' } });
BackboneJS Collections:
BackboneJS Collections can be simply defined as a container which maintains the list of BackboneJS Models in an organized way.
var EmployeesList = Backbone.Collection.extend({ //Specifying the model class that the collection contains. Employee model has already been created in BackboneJS Model Section. model: Employee }); //Initializing Collection this.collection = new ExployeesList(); //Adding Object in Collection this.collection.add(employee); //Iterating Whole Collections _(this.collection.models).each(function(employee){ //Processing fetched object from collection }, this);
BackboneJS Routers:
Not heard about word routers before? Well, Routers were previously called controllers, before they got a change of name in BackboneJS version 0.5. So, Routers are basically a mechanism to route client side pages and connect them to events and actions through URLs. So if you want to make reference to certain state or location of a web application you need it. Consider the following example to understand how we can use them:
var Workspace = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/kiwis "search/:query/p:page": "search" // #search/kiwis/p7 }, help: function() { ... }, search: function(query, page) { ... } });
BackboneJS Events:
Events are one of the strong component of BackboneJS. Events are used to create a relationship between your application and browser features. Furthermore, It gives the ability to perform some action on happening something to object.
We will be understanding Events by discussing its usages in different scenarios with examples.
BackboneJS DOM Events
All jQuery Events are valid for BackboneJS to bind. To use BackboneJS Events you need to define an attribute named “events” into your views with the following syntax:
“event css-selector” : “function”
Where event is the kind of Event that you want to handle/listen, then you need to add a blank space and use a css selector (as you do with jQuery), but remember that the scope of the bind will include only those elements that belongs to your View. function is a name of a method of your view, and must be passed as string.
Let’s Consider an example to understand this thoroughly:
var EmployeeView= Backbone.View.extend({ el: $('body'), // el attaches to existing element //So, Here we are binding events on adding each employee. Whenever DOM object with id 'addEmployee' will be clicked a new employee record will be added and 'emplyeeAdded method will be called. events: { click #addEmployee: 'employeeAdded' }, initialize: function(){ _.bindAll(this, 'render', 'empoyeeAdded'); this.counter = 0; // total number of employee added so far this.render(); }, //render() now introduces a button to add a new employee on which we have binded an event above render: function(){ $(this.el).append("<button id='addEmployee'>Add list item</button>"); $(this.el).append("<ul></ul>"); }, //Function that will be called each time a new employee will be added empoyeeAdded: function(){ this.counter++; $('ul', this.el).append("<li>Employee Added with id: "+this.counter+"</li>"); }, }); var employeeView= new EmployeeView();
Here you can have All Possible Events Categories for detailed understanding of Events Usages.
We can also bind events on objects level as well, such as:
events: { 'click' : 'confirmation' } confirmation: function(){ alert("Employee Added Successfully...!!!"); }
Model Binding Events
Usually a view tracks a model, and when the data in the model changes the view is updated to represent the changes. But our views did not track models and were not updated when the model changed. So, we will have to track changes to the models so that we may change our models too accordingly. Hence here the role of bindings events to our models comes into play. So, we will be attaching events with change of our models which will invoke methods to change our view as well accordingly.
Let’s consider an example about how can we bind events to model and change the views accordingly whenever there is any change in the model:
//Here we have Employee Model var Employee = Backbone.Model.extend({ defaults: { name: 'BAY', gender: 'male' } }); //Collection of Employees var EmployeeList = Backbone.Collection.extend({ model: Employee }); //In our initialize method we will bind events to change in models initialize: function(){ _.bindAll(this, 'render', 'unrender'); // every function that uses 'this' as the current object should be in here //Binding for events whenever any model object will be changed, to change view also this.model.bind('change', this.render); //Binding for events whenever any model object will be removed, to change view also this.model.bind('remove', this.unrender); } //This method will update the view when model object will be removed unrender: function(){ $(this.el).remove(); } //To update the view when model object will be changed to show the updated values render: function(){ $(this.el).html('<span style="color:black;">'+this.model.get('name')+' '+this.model.get('gender')+'</span>'); return this; // for chainable calls, like .render().el },