Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js Overview: Developing Backbone.js examples for beginners

In this article we will see an overview about the JavaScript framework called Backbone.js. We will learn how to work with this powerful tool built in Javascript.

What is Backbone.js?

Backbone.js is a basically lightweight JavaScript library, which allows structuring and organizing JavaScript code based on Model, View and Controller (MVC) pattern. It works very well with any of the JavaScript libraries and used most in the web development community because of:

  • Its ease to use
  • Provides structure to the JavaScript applications.

Jeremy Ashkenas created Backbone in 2010. It is based on the Underscore.js library, which provides many functions to work with arrays, collections, objects, events and so on. It is literally a backbone upon which you build your application and provides a set of base classes to create clean JavaScript code with a RESTful JSON interface on your server. The single page web applications or client side applications can be developed using this library.

History

We have been using web application development process for more than 2 decades now. The web applications were just static html pages at the beginning stage and developers had to change the HTML, CSS and JS code to change the content. The data had to be shared among multiple users and stored at a central location. This led to development in distributed web applications. The distributed applications were capable of providing interactive user experience and web applications provided very limited features.

Later, the browsers became more capable and HTML became more mature. The applications were created by using browser based client side technologies such as JavaScript code. The main reason was to create a single page application which allows creating interactive applications and providing interactive experience to the user. So to create single page applications, there is a need for JavaScript framework and libraries, which provide some structure to single page applications. Web applications need more usage of JavaScript to generate the content. JavaScript allows changing the content without reloading the whole page for every request. Sometimes lack of structure makes code hard to maintain.

Nowadays, we have few open source JavaScript frameworks available to solve problems of creating single page applications and large JS web application. This is where, Backbone comes into play. It designs our applications in a structured manner and increases maintainability. It is one of the most widely used frameworks and used in number of big companies like Groupon, Khan Academy, Pandora, Wordpress, and so on.

Architecture of backbone.js

Architecture of backbone.js

Figure 1: Architecture of backbone.js

The above diagram represents the architecture of Backbone.js.

  • User requests a file such as a web page, image etc from a web server using HTTP Request protocol.
  • The Backbone routers are used for routing applications’ URLs when using hash (#) tags. A router is required when web applications provide linkable, bookmarkable, and shareable URLs for important locations in the app. It provides methods for routing client side pages and connecting them to actions and events.
  • The DOM (Document Object Model) is an application programming interface which defines the logical structure of documents and the way a document is accessed and manipulated. The DOM sends events to the view.
  • The view objects are associated with a fragment of DOM and constitute the user interface in an application. They are designed to tie models that need to present to the user. View can change as model changes.
  • The model moves the events to data source to get requested information of the user. The models are the heart of a JavaScript application which provides basic set of functionality for managing changes. They take specified requested data from the database, synchronize it, and update the view and DOM.

For information about Backbone.js, just visit the website at the link session.

Features of backbone.js

  • It can be integrated easily with other frameworks, so it is called as minimalistic.
  • It uses only required functionality wherever necessary in the application.
  • It has OOP design and can be easily extended and overridden.
  • It contains over 100 available extensions.

Note: All the examples in this article contains jquery.min.js, underscore-min.js and backbone-min.js libraries within the tag which supplies structure to JavaScript applications by providing rich API of enumerable functions, views etc. Here we are using CDN files.

Example

The following is a simple example, which shows backbone view click to display specified message when link is clicked.

Listing 1: HelloWorld.html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
      var AppView = Backbone.View.extend({
          events: {
              // here element is link, you don't have to specify its id there
              'click': 'hello'
          },
          //creates alert box to display the message
          hello: function(){
              alert('Welcome to Backbone.js...');
          }
      });
      $(document).ready(function() {
       //create a new view instance
        var app_view = new AppView({
 // here we are attaching the view to the existing element
          el: '#new'
        });
      });
    </script>
  </head>
<body>
<a href="#Click Here" id="new">Click Here</a>
</body>
</html> 

Details of the code:

  • The example explains how to display the message when we click the link on the output page using Backbone.js.
  • Create main view of the application called App which is bound to the #new form.
  • Create a click event called hello to display the message using alert box.
  • The code inside $(document).ready () will run only once when the Document Object Model (DOM) is ready for JavaScript code to execute.
  • The line var app_view = new AppView initializes the view before loading the message.
  • The view can be attached to existing elements by using el: '#new'. The el stands for element in which, every view has an element associated with the HTML content, will be rendered. This id can be used within an anchor tag which displays the message when user clicks on the link.

Output

  • Save the file as HelloWorld.html in your system.
  • Just open the file in the browser, you will get a link, Click Here, on clicking this you will get an output as in the image below.
HelloWorldExample

Figure 2: HelloWorldExample

The Backbone.js library gives structure to web applications by providing models, collections and views, all hooked up together with custom events. Models represent key value binding and custom events, collections provide rich API functions, views for handling events, which connect the application to backend via RESTful JSON interface and automatically save and fetches the data.

In the following sections we will study about Backbone’s modules in order to understand the core concepts behind the backbone.js before you start building applications using it:

  • Views
  • Models
  • Collections
  • Events
  • Routers

Let’s begin with, one by one in detail.

Views

Backbone views are responsible for how and what to display from our application. They don’t contain the HTML markup for the application; they provide idea behind the presentation of the model’s data to the user. Views are used to reflect “how your data model looks like”. It has its own DOM element which knows about its model or collection. It handles the user input events and binds the model events and model methods and renders model or collection and interacts with the user.

It represents the logical chunk of UI in the DOM i.e. view classes do not know anything about the HTML and CSS. Each view can be updated independently when model changes without reloading the whole page. It allows defining DOM events declaratively without having to worry about render function to the model into HTML using a template data.

Consider the above example (Listing 1):

We can create the backbone view by simply extending the existing View class of the backbone i.e. Backbone.View which creates initial element outside of the DOM, if existing element is not provided.

var AppView = Backbone.View.extend({
….
});

We can override the initialize and constructor of the backbone views as shown below:

  var AppView = Backbone.View.extend({
  hello: function(){
              alert('Welcome to Backbone.js...');
   }
});

The hello() function is always called when instantiating backbone view. A view can be instantiated using the new keyword as show below:

var app_view = new AppView;  

Understanding the “el” property

A view "el" is where all the event binding takes place. You don’t have to use it but if you want backbone to fire events you need to do rendering work on the el. It tells the view which element to use as the view reference, whether they have been already created or not. An "el" is a DOM element and every backbone view has “el” property. The DOM element can be accessed with the el property.

View can be created in two ways:

  1. Create a view associated with existing DOM element.
  2. Create a view which will have its own DOM element.

We can create a view for existing DOM element as show below:

var app_view = new AppView({
el: '#new'
});

Let’s create a view which creates DOM element dynamically as shown below:

<div id=”my_app”></div>
  var AppView = Backbone.View.extend({
  hello: function(){
              alert('Welcome to Backbone.js...');
   }
});
var app_view = new AppView({
          el: '#new'
 });
 

Example using el property:

The following example shows usage of el property:

Listing 2: el_Property_demo.html

<!DOCTYPE html>
<html>
  <head><title>HelloWorld</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <div id=" app_demo "></div>
	<script type="text/javascript">
	    AppView = Backbone.View.extend({
	        initialize: function(){
	            alert("Hello !!!! This is el property...");
	        }
	    });
	    var app_view = new AppView({ el: $("# app_demo ") });
	</script>
  </head>
<body>
</body>
</html> 

As shown in the script, we are setting view’s “el” property to div id “app_demo” which makes Backbone.View owner of the DOM element. The code binds the container element and any event that we trigger must be in this element. Save this file as el_Property_demo.html.

When we run the script, the specified message will get displayed using alert box as shown in the below output picture:

EL_PropertyExample

Figure 3: EL_PropertyExample

Models

In the MVC pattern, models represent business entities with some business logic and business validations. Models contain data of an application and logic of the data and represents basic data object in the framework. Sometimes models are called the heart of JavaScript application as they contain all application data. They are mainly used for data storage and business logic. It can be retrieved from and saved to data storage.

By using models, it is possible to validate the data, store the data, and provide access control to different parts of the data in the application. They contain bunch of data and methods for performing related operations and computations on the particular data. Models are important building blocks for developing backbone.js applications.

Lets create one simple model:

Listing 3: Model_Demo.html

<!DOCTYPE html>
<html>
  <head><title> Model Demo</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
	MyApp = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to model...");
        }
    });
    var myapp = new MyApp;
    </script>
      </head>
    <body>
    </body>
</html>

When we run the script, the specified message will get display using alert box as shown in the below output picture:

ModelDemoExample

Figure 4: ModelDemoExample

As shown in the above script, we can create model as follows:

MyApp = Backbone.Model.extend({
});

Model can be created simply by extending the backbone model class. Whenever we create the model, backbone will call initialize function as shown in the above example. This function can be used to add custom behavior to the model. Whenever we create instance of a model, initialize () function get triggered.

Setting and Getting Attributes

We can pass parameters to the instance of the model by setting hash of attributes on the model. The value of an attribute can be set by using set () method and get the value of an attribute by calling get () method in the model.

The syntax for set and get attributes can be written as shown below:

model. set (attribute)
model. get (attribute)

Let’s see one simple example for these attributes:

Listing 4: Attributes.html

<!DOCTYPE html>
<html>
  <head><title>Set and Get Attributes</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
    var  Person = Backbone.Model.extend();
    var person = new Person();
    person.set({ name: "Mahantesh"});
    alert(person.get('name'));
   </script>
 </head>
<body>
</body>
</html>

In the above script, we have created the model simply by extending the backbone model class. The instance of the model is created by using new keyword. The set () method is used to set the value of an attribute as “Mahantesh” and get () method is used to display the value of an attribute by using alert box.

When we run the script, the get () method will display the value of an attribute by using alert box as shown in the below output picture:

Set_GetAttributesExample

Figure 5: Set_GetAttributesExample

Collections

Collection is quite similar to creating model which is ordered set of models. Collections contain list of models that can be processed in the loop and support sorting and filtering. When creating a collection, we can define what type of model that collection is going to have along with instance of properties. Any event triggered on a model, which will also trigger on the collection in the model.

To create collection class of your own, we just need to extend the backbone’s collection class as shown below:

var MyApp = Backbone.Collection.extend({
});

Adding models to a collection

We can add models to a collection with some data as shown in the below example:

Listing 5: Collection.html

<!DOCTYPE html>
<html>
  <head><title>Set and Get Attributes</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
     var MySong = Backbone.Model.extend({
           defaults: {
               name: "Not specified",
               artist: "Not specified"
           },
           initialize: function(){
               console.log("Music is the thing that makes you forget the whole world!!!");
           }
       });
       var MyAlbum = Backbone.Collection.extend({
           model: MySong
       });
       var song1 = new MySong({ name: "Take On Me", artist: "Christina Aguilera" });
       var song2 = new MySong({ name: "Dancing Queen", artist: "Todd Agnew" });
       var song3 = new MySong({ name: "Knowing Me, Knowing You", artist: "Priscilla Ahn" });
       var myAlbum = new MyAlbum([ song1, song2, song3]);
       console.log( myAlbum.models );
 </script>
 </head>
<body>
</body>
</html>

As we know, model can be created simply by extending the backbone model class. Whenever we create the model, backbone will call the initialize function as shown in the above script. This function can be used to add custom behavior to the model. Whenever we create instance of a model, initialize () function get triggered.

The collection can be created simply by extending the backbone’s collection class. Once we specify the model property of a collection, later on whenever we create this collection, it will create an array of the specified models i.e. it creates array of models song1, song2 and song3 as specified in the code.

The line var myAlbum = new MyAlbum([ song1, song2, song3]); uses new keyword for instantiating a collection and added model objects in the collection while creating it. When we run the script we will get result in the console as shown in the below output picture:

CollectionExample

Figure 6: CollectionExample

Adding and Removing Models

If we want to add models to a collection, use the add () method and to remove models from a collection, use the remove () method. If we are adding models to a collection that are already in the collection, they will be ignored. The add () and remove () methods can be used as follows:

collection. add (models, [options]);
collection. remove (models, [options]);

The following simple example shows usage of add () and remove () methods:

Listing 6: Add_Remove_Models.html

<!DOCTYPE html>
<html>
  <head><title>Add_Remove Models</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
	var MyApp = Backbone.Model.extend({
		defaults: {
		country: '',
		completed: false
	  }
	});
	var MyCollection = Backbone.Collection.extend({
	  model: MyApp,
	});
	var a = new MyApp({ country: 'india'}),
		b = new MyApp({ country: 'australia'}),
		c = new MyApp({ country: 'england'});

	var AppSize = new MyCollection([a,b]);
	console.log("Collection size: " + AppSize.length); //Collection size: 2

	AppSize.add(c);
	console.log("Collection size: " + AppSize.length); // Collection size: 3

	AppSize.remove([a,b]);
	console.log("Collection size: " + AppSize.length); // Collection size: 1

	AppSize.remove(c);
	console.log("Collection size: " + AppSize.length); // Collection size: 0
 </script>
 </head>
<body>
</body>
</html>

As shown in the script, add () and remove () methods accept both individual models and list of models. The collection can be created simply by extending the backbone’s collection class and with model name “MyApp”. We are using three variables a, b and c assigning different country name respectively by using model name “MyApp”.

First, we are adding a and b which brings up the collection size as 2. Next, by adding the last value c, the collection size will be 3. Adding of items to a collection can be done by the add () method.

If you want to remove a and b from the collection, write as “remove [a, b]” which makes size as 1 and lastly after removing the last variable c which makes the collection size 0. The result of all these operations can be seen in console.log of the browser.

When we run the script we will get result in the console as shown in the below output picture:

Add_Remove_ModelsExample

Figure 7: Add_Remove_ModelsExample

Router

Router is similar to hook menu which defines paths and callbacks. Backbone routers are used for routing application URLs when using hash (#) tags i.e. it is an URL representation of application’s objects. The URL is changed manually by the user. The URL is used by backbone so that it can understand what application state to be sent or present to the user. Router is required when web applications provide linkable, bookmarkable, and shareable URLs for important locations in the app.

The router can link views based on its application state. It is responsible for loading the data and displaying templates. It provides methods for routing client side pages and connecting them to actions and events. When router maps URL, it triggers the actions and events for the matched routes. It is still very useful in providing URL routing facility for an application. In URL routing, anything after hash (#) tag is interpreted by the router.

Few years ago, there was no separate URL for each single page applications. The browser was not capable of displaying separate pages for separate screens. In the present situation, the above operations can be handled with single page applications by using backbone routes.

The following example shows how router maps to a particular route when user clicks on the link:

Listing 7: Router.html

  <!DOCTYPE html>
<html>
  <head><title>Router</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
   <script type="text/javascript">
	var RouteMenu = Backbone.View.extend({
		el: '#routemenu',
		events: {
			'click a' : 'onClick'
		},
		onClick: function( e ) {
	        		router.navigate('/');
		}
	});
	var Router = Backbone.Router.extend({
		routes: {
			'route/:id' : 'defaultRoute'
		},
	});
	// Run example's components
	var routemenu = new RouteMenu();
	var router = new Router();
	Backbone.history.start();
	</script>
</head>
<body>
    <section id="routemenu">
        <ul>
            <li><a href="#/route/1">route 1</a></li>
            <li><a href="#/route/2">route 2</a></li>
            <li><a href="#/route/3">route 3</a></li>
        </ul>
    </section>
</body>
</html>

When we click on the route 1, route 2 and route 3 and observe the UI changes to the action triggered by the mentioned links. When you click route 1 more than one time, the link seems to not trigger any action.

We have created the menu view called “RouteMenu” and trigger router’s reset action each time when clicking on the link. We can call the same route multiple times by clicking the same link.

Next, we have created the router model which translates URL requests into actions. The routes configuration is created by using “route/: id”. The line “Backbone.history.start ();” starts backbone history for bookmarkable URLs. When we run the script, we could see the URL is getting changed in the address bar of the browser.

When we run the above example, we will get following output picture:

RouterExample

Figure 8: RouterExample

Events

Events are the basic inversion of control and capable of binding objects and trigger custom events i.e. we can bind custom events by using desired name of our choice.

The simple format of event can be written as below:

var object = {};
_.extend(object, Backbone.Events);
object.on("alert", function(msg) {
 	 alert("Event triggered... " + msg);
});
object.trigger("alert", "an event");  

As shown in the code, we have declared an empty object which can be extended by using underscore functionality called “_.extend” because underscore is backbone’s hard dependency. The _.extend functionality has syntax as, _.extend (destination object, source object).

Therefore we could use the properties and methods from the source object. Moving forward, alert event is bind with event object by using object.on () method which takes parameters such as events and callback. We are using alert as event and JavaScript alert for displaying the message using alert box. The last line “object.trigger” triggers the event specified in the first argument and also we can pass optional arguments as specified in the code.

Here we saw the basics of Backbone JavaScript library. The source code of the above examples is attached below. You can execute and play around to understand this JavaScript better.

Links



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login