Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Getting started with Backbone.js.

4.80/5 (7 votes)
2 Oct 2014CPOL5 min read 17.7K  
What is Backbone js and why to use it

Introduction

This article is targeted at novice to intermediate developers wishing to learn how to better structure their client side code using backbone.

Developer often confuse with the whole purpose of backbone.js.

What the heck is Backbone...Why do I even need it ....What is the whole purpose of using it....??

Image 1

Background

Traditionally, the whole of data was pushed from server to browser on page complete. There was less interaction of data in client side using JavaScript. Nowadays. these concepts have been reversed - client application pulls data from server and renders the data when and where it is required.

Consider a typical style web application like ASP.NET MVC. We have some data being passed from controller to view and then is being rendered on browser. An end user interacts with these data, this is where backbone comes into the picture. These frameworks help a developer to put things in the right way in their proper place, so that we can maintain an application through years and scale out its complexity without creating a mess.

Backbone allows us to create a user experience using JavaScript and Ajax which allows us to build complex UI. Structure code elegantly using backbone.

The official definition from backbone.js is as follows:

Quote:

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

SPA

Single Page Application (SPA): It is a concept, not proper definition. The page does not reload at any point in the process, nor does control transfer to another page. This technique is used to improve user experience and it delivers the content faster. This model is a result of evolutionary process. In the beginning, web pages were just connected set of static pages. After that came in the server side concepts where each user action resulted in a server side request which would again reload the whole page. In this model, the user is consistently interrupted by network latency, actual performance suffer due to constantly regeneration of web pages. After that, client side scripting and AJAX came in which increased user experience to a great extent. SPA is a hybrid model of web development. Majority of the logic and code is written in client side.

Advantages of SPA

  • No round tripping
  • Loads all of its resources at one go
  • Rich user experience
  • Net latency is reduced
  • Performance is increased
  • E.g.: Gmail, twitter
So What's the Point of Using Backbone in this...??

Creating client side application with such complex UI is a tough nut to crack. Developing a coherent, readable, structured, testable and maintainable client-side application is not easy. Without using a framework, it finally results in a mess. Backbone has the power to maintain such complexity and also reduces the difficulty of maintaining the code.

The Backbone Effect

Image 2

Building up of SPA or complex UI interface will become extremely difficult if we use only JQuery. JavaScript libraries are great but they do not provide any structure to code, maintenance is a nightmare and finally, we would end in a code which would look something similar to the first image. :)

Backbone provides a proper structure to code. It follows a kind of MVC pattern on the client side and makes the code modular.

With use of backbone, the entire communication with the server can be done through RESTful API. Nowadays, browser are not the only client various mobile devices, tablets, etc. A web site needs to be compatible in all of these devices. Backbone makes it pretty easy for developers to build such application and maintenance is also cool.

There are a lot of other advantages as well which can be found out here.

Prerequisites

Before starting up with backbone, a developer needs to be familiar with the following things:

  • Basic understanding of JavaScript
  • HTML, CSS, Web Programming Knowledge
  • DOM manipulation using JQuery
  • Firebug/WebKit - Debugging tool

Required Dependencies

  • Underscore.js - It's a library that provides functional programming support for JavaScript. Backbone provides many functions for manipulating collection.
  • JQuery/Zepto - All of DOM manipulation is done using JQuery, also all of the Ajax calls are made from this. Zepto is an JQuery alternative.

Backbone Structure

Backbone provides a set of tools for introducing structure into client-side apps.Image 3

Models - It provides data for application, we require a persisting model which helps us to edit and update model. The most recent state of model can be saved stored somewhere like web browser localstorage or data can be synchronized with database. A single Model can be used against multiple Views. If any changes are made to model, event can be fired based upon the requirement. The beauty of backbone Model is that it's not concerning the way in which view is rendered.

JavaScript
var Person = Backbone.Model.extend({
     initialize : function(){
               console.log("Welcome to learning of backbone");
       }
});

var p = new Person();

Collection - Collections are simply ordered group of models. They fire from model. They also contain events of their own. Collection depends upon models.

JavaScript
var PersonList = Backbone.Collection.extend({
         model : Person
});

var list = new PersonList();

View - View interacts with DOM. It handles events from model, collection and DOM. It is basically used to show what the model data looks like along with templates used like underscore.js. Whenever user interacts with element, any changes made are being handled by controller and not view.

JavaScript
var PersonView = Backbone.View.extend({
       collection : list,
       initialize : function() {
             console.log("An initialize is always called 
                          when a new object is created of the view");
        }
});

var pview = new PersonView();

Routing - In Backbone, routers provide a way for you to connect URLs (either hash fragments, or real) to parts of your application. Any piece of your application that you want to be bookmarkable, shareable, and back-button-able, needs a URL. Route interprets anything after "#" tag in URL.

For example:

JavaScript
 var personRouter= Backbone.Router.extend({
        routes: {
            "user/:id" : "getTodo", // matches http://demoapp.com/#user/1
            "*actions": "defaultRoute" // matches http://demoapp.com/#anything-here
        },
        getUser : function(){
            console.log("router for user");
        }
        defaultRoute: function(){
            console.log("default router");
        }
    });
    
    // Initiate the router
    var router = new personRouter;
   
    // Start Backbone history a necessary step for bookmarkable URL's
    Backbone.history.start();
});

Points of Interest

Getting started with Backbone is pretty much easy and simple. The beauty of backbone is the way it renders data into DOM and how it handles the data. It works on RESTful architecture and deals with JSON data. Backbone is a very strong JavaScript library which leaves us with a code that is maintainable in the long run.

Happy coding !!!

History

  • 2nd October, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)