Home » JavaScript » Backbone.js » Backbone.js Events Example

About Bilal Ahmed Yaseen

Bilal Ahmed Yaseen
Bilal is professional, experienced and qualified software engineer involved in the design and development of various business and enterprise applications. He has best problem-solving, imaginative, innovative and excellent communication skills. He graduated from One of the most prominent University of Pakistan, Punjab University College of Information and Technology. He works as a Software Engineer in the multinational organization where he is mainly involved in the enterprise applications based on Java, Groovy & Grails and MySQL Server.

Backbone.js Events Example

The purpose of this tutorial is to provide basic understanding of backbone.js along with its components. We will be discussing that what backbone.js actually is and how it differs from other JavaScript libraries. In particular, we will be understanding its out of the box support for events with example.

We will start from the very first step which is to set up a working environment for backbone.js to start working with it. Then we will provide a brief overview, explain the support for events and finally provide a comprehensive working example.

Actually, this example will be completed step by step with the implementation of the component that we will be discussing, in order to give some proper insight and understanding of what you are reading.

Tip
If you already have BackeboneJS set up in your system, you may jump directly to the Understanding BackboneJS below.

Want to be an jQuery Ninja?

Subscribe to our newsletter and download the jQuery Programming Cookbook right now!

In order to get you prepared for your jQuery development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

 

Setting up Working Environment for Backbone.js

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:

  1. Backbone.js
  2. Underscore.js (>=1.4.3)
  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>

The picture below shows the necessary files downloaded in order to start working.

Backbone.js Essential Files

Backbone.js Essential Files

You can simply run the above HTML file on browser to see that JS files have been loaded successfully or not.

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:

  1. Views
  2. Events
  3. Models
  4. Collections
  5. 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: 'bilal',
address: 'Pakistan'
 }
 });

For more Details regarding BackboneJS Model please refer: BackboneJS Model in Detail

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);

For more details regarding BackboneJS Collections please refer: BackboneJS Collections in Details

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) {
 ...
 }
});

For more details regarding BackboneJS Routers please refer: BackboneJS Routers in Detail

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...!!!");
 }

So, whenever any object is clicked, this call back method will be called.

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
 },

For more details regarding BackboneJS Events please refer to: BackboneJS Events in Detail

Download the Sample Application Source Code

In this article we created some sample applications starting from a very basic one, covering all the BackboneJS components.

Download
You can download the full source code of this example here: BackboneJS Sample Applications

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

2 comments

  1. Nice tutorial to grasp the concepts. Do you have any backbone tutorials that end up in building a working app?

  2. Bilal Ahmed Yaseen

    You can download the very simple examples from the Download section of this article. These Examples contains the usages of all of the components of BackboneJS.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook