Search the site:

Copyright 2010 - 2024 @ DevriX - All rights reserved.

Backbone.js: A Detailed Guide for Beginners

If you’re a seasoned JavaScript front-end developer, you would have definitely heard of Backbone.js – an extremely lightweight JavaScript library that makes the process of creating complex single page applications (SPAs) so much easier. Created by Jeremy Ashkenas, the author of CoffeScript language, this JavaScript library has gained tremendous popularity among web developers due to its low barrier to entry – it’s quite easy to learn and simple to use.

This blog post is to give you a taste of Backbone.js. After reading this short guide, you’ll learn what Backbone.js is, how to get started, and what its main features are.

So let’s dive into Backbone.js!

Backbone.js: An Overview

Backbone.js, often referred to as Backbone, is an open-source JavaScript library designed with the aim of providing structure to rich client-side web applications. Based on the traditional Model-View-Controller (MVC) design pattern, it ensures that the communication between a server and a client is done entirely through a RESTful JSON API. Moreover, it’s known not only for being incredibly lightweight (under 8kb) but also for keeping various components of a web application in sync. To provide you with a platform for building clean and maintainable applications, Backbone.js sits on top of Underscore.js (another JavaScript library) and jQuery.

There was a time when web applications used to be static HTML pages and required programmers to change the HTML, CSS and JS code in order to make changes in the content. With the evolution of server-side programming languages like Java, PHP and Ruby etc, static HTML pages have became generated dynamically. And so, this is the approach that most of the web applications use today.

The main problem with this approach is the heavy use of JavaScript, which makes the application code extremely difficult to organize and maintain. That’s where Backbone.js comes into play as it provides developers a more structured approach to build JavaScript-heavy web applications.

Getting Started with Backbone.js

Before we get down to business, here are the top 8 common Backbone.js developer mistakes that you should avoid.

To use Backbone.js, you first need to download three JavaScript libraries – Backbone.js, Underscore.js and jQuery. Once downloaded, put all these three libraries into the js folder of your application and load them in your index.html page as follows:

My First Backbone.js Application

<script src="js/jQuery.js"></script><script src="js/underscore.js"></script>
<script src="js/backbone.js"></script>

Alternatively, you can also reference “minified versions of all these libraries” as follows:

My First Backbone.js Application
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="https://documentcloud.github.com/backbone/backbone-min.js"></script>

Whatever method you’re using, make sure to load these files in the following order:

  1. jQuery
  2. Underscore
  3. Backbone

Otherwise, your application may not function as it should.

Now, to check whether or not Backbone.js is installed properly, open your index.html file in Chrome. Open “Developer tools” via the Chrome menu and navigate to the “Console” tab. If the installation is successful, you will have access to the global variable Backbone.

Key Features of Backbone.js

While a traditional MVC stands for Models, Views and Controllers, the MVC in Backbone has a slightly different meaning. Since there are no controllers in Backbone.js, it sometimes referred to as an MV* framework. Unlike most of the MVC frameworks, Backbone.js consists of six main components: Models, Views, Collections, Events, Routers and Sync.

Let’s go through them one by one!

Models:

In Backbone, models contain the interactive data for an application as well as a large part of the logic – such as access control, default values, data validation, conversions, computed properties, data initialization and so on – associated with that data. Moreover, they notify other objects in your application about the changes in a specific attribute. To put it simply, Backbone models provide you with a great way to manage all your domain-specific entities. The following is a simple example of creating a model with Backbone:

var Employee = Backbone.Model.extend({
initialize: function(){
alert("Welcome to Backbone");
},
defaults: {
name: 'Robert',
age: 23,
occupation: 'Worker'
}
});

In the above code, I’ve defined the initialize function which will be fired when the model is created. I’ve also set some default attributes, in case no parameters are passed.

Views:

Views in Backbone are quite different from the traditional views that you usually find in a MVC framework like Rails. Factually, Backbone Views determine nothing about your application’s HTML/CSS markup. Instead, they contain the logic behind the presentation of model’s data that needs to be presented to the user. Unlike the traditional MVC pattern, Backbone’s Views not only act like “Controllers” but also play well with popular JavaScript templating libraries. Fundamentally, a Backbone view is responsible for:

  • Organizing the interface into logical views.
  • Listening to events and reacting accordingly.
  • Detecting changes in the model and rendering them on the HTML page.

Let’s create a simple view:

var EmployeeView = Backbone.View.extend({
tagName: "li",
className: "employee",
events: {
"click": "alertTest",
"click .edit": "editEmployee",
"click .delete": "deleteEmployee"
},
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );
}
});

Using the tagName attribute, I’ve specified the HTML element tag (li) that will be used to wrap the view. The initialize function monitors all the changes made in a model and executes the code immediately after a new model instance is created.

Collections:

Collections, as the name itself suggests, are essentially just an ordered sets of models. They prove to be extremely useful when you want to define multiple instances at once. For example, you can take advantage of a collection instead of defining 10 employees individually. Just like models, they also fire a change event every time a model is removed or added to the collection. A collection in Backbone can be defined as follows:

var PeopleCollection = Backbone.Collection.extend({
model: Employee
});

In this example, People is a Collection of the Employee model. Remember, a Collection can only store a single type of model and you must define which model you want a collection to store.

Events:

Events are a module in Backbone, which can easily be mixed into the other classes, including Backbone.Model, Backbone.View, Backbone.Collection, Backbone.History and Backbone.Router. They give other Backbone objects the ability to bind and trigger custom events.

If you remember, I’ve added three .click events – alertTest, editEmployee and deleteEmployee – to the Employee view. The first event alertTest lets you test out your click functionality when you click on a model in the view. For that, you have to comment out the alertTest as follows:

events: {
"click": "alertTest",
"click .edit": "editEmployee",
"click .delete": "deleteEmployee"
},
alertTest: function(){
alert('Click event is working properly');
},

If you don’t do so, you’ll continuously receive the alert message when you click to edit or delete. You can add two buttons, edit and delete, in index.html as follows:

<script id="employeeTemplate" type="text/template">// <!&#91;CDATA&#91;
<span><strong><%= name %></strong> (<%= age %>) - <%= occupation %></span>
 <button class="edit">Edit</button> 
 <button class="delete">Delete</button>
// &#93;&#93;></script>

Now, let’s bind click events:

events: {
'click .edit' : 'editEmployee'
'click .delete' : 'destroyEmployee'
},

editEmployee: function(){
var newName = prompt("Enter a new name", this.model.get('name'));
this.model.set('name', newName);
}
destroyEmployee: function(){
this.model.destroy();
}

Finally, modify the initialize function to reflect any changes made to the model in the view:

initialize: function(){
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},

Routers:

In Backbone, routers provide you a great way to connect client-side URLs to actions and events in your application. Because they interpret anything after #, the URL you’re connecting must contain #. Consequently, they are quite helpful when you want a URL to determine the view that will be rendered to the user. You can define a router as follows:

App.Router = Backbone.Router.extend ({
});

Now, let’s define a hash tag route:

App.Router = Backbone.Router.extend({
routes: {
'edit/:id': 'edit'
},
edit: function(id){
$(document.body).append ("Edit route with id: ' + id");
}
});
var newRouter = new App.Router;
Backbone.history.start();

Backbone.history, which serves as a global router, handles hashchange events or pushState in your application. Now, if you open index.html in your browser, you would see a string like this:

file://…backbonejs/index.html#edit/5

Sync:

Sync in Backbone.js is responsible for mapping the state of the model to the server side databases. The Backbone.sync function is called every time Backbone attempts to read, save, or delete a model from the server. Additionally, it makes use of jQuery or Zepto’s $.ajax() implementations to make a RESTful JSON request , however, you can override it according to your strategy. Internally, Backbone.js maps CRUD to REST like so:

var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};

And, the Backbone.sync has the following method signature:

Backbone.sync = function(method, model, options) {
};

Where,

  • Method is the CRUD (create, read, update, patch or delete) method.
  • Model is the model to be saved or collection to be fetched.
  • Options include success and error callbacks.

So, that’s all there is to Backbone.js and its main components. If you want to know more about this super-lightweight JavaScript library, then you may go through the official documentation.

Author Bio:

Ajeet is a senior web developer at WordPressIntegration – PSD to WordPress service provider, where he is responsible for writing custom JavaScript code during the conversion process. In his spare time, he writes on different topics related to JavaScript, WordPress, and Web Design to share his work experience with others. You can follow WordPressIntegration on Facebook