Traditionaly, the whole of data was pushed from server to browser on page complete. There was less interaction of data in client side using javascript.Now a days these concepts have been reversed - client application pulls data from server and renders the data when and where its required.
Consider a typical style web application like Asp.Net MVC. We have some data the 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 framework helps a developer to put things in right way in their proper place , So that we can maintain application through years and scale out its complexity without creating a mess.
Backbone allows us to create user experience using javascript and ajax which allows us to build complex UI. Structure code elegently using backbone.
What is BackBone.js
Backbone.js is a lightweight framework that lets us create single page applications in a structured manner. It is based on the Model-View-Controller (MV*) pattern. It is best suited for creating single page applications using a RESTful service for persisting data.
Now one might wonder what is this MV*. we have talked about the MVC architecture at length and then we are saying that backbone is a MV* framework. Well the reason for this is that backbone does not want to enforce the use of controllers. Applications can choose to hook their own code to be used as controllers, use some plugin that can provide a controller or perhaps use MVVM pattern instead of MVC pattern.
Background:
It was a long time ago (almost a decade back) when most software applications were getting built as standalone applications. These applications were targeted at a single user and ran on their operating systems. Then came the need to share data across multiple users and a need to store data at a central location. This need gave birth to distributed applications and web applications. Distributed applications ran as standalone applications on the user’s machine giving him a rich user interface (desktop like experience) to work with, and behind the scenes, these applications sent data to a server. Web applications, on the contrary, were sandboxed in a web browser and HTML and HTTP were used to let the user perform operations on the data which is stored on the remote server.
The major differentiating factor for these two applications was that the distributed applications provided an interactive user experience whereas web applications provided very limited features (due to technology limitations). The downside of distributed applications was that it was very difficult to roll-out and ensure the application updated across all users. Web applications had no such problems because once the application is updated on the server, all users got the updated applications.
Both these approaches had pros and cons and something needed to be done to get the best of both worlds. This is where browser plugin based applications like Flash applications and Silverlight applications came into picture. These technologies filled in the gap for all the functionality not possible with HTML. They provided the possibility of creating rich internet applications that ran in the browser. The only downside of this was that the user needed to install the browser plug-in to get these applications to work.
Then came the time when browsers became more capable and HTML became more mature. Creating a rich internet application became possible only using browser based client side technologies. This led developers to write client side code using HTML and JavaScript to create rich internet applications. No need for plugins like Flash and Silverlight. But since HTML and JavaScript were never meant to be used for writing full fledged web applications, these applications had all the HTML and JavaScript code intermingled. This led to spaghetti code and these client side HTML/JavaScript applications (Single Page Applications or SPAs) became a maintenance nightmare.
So why should we write single page apps when they lead to bad code? The main reason for wanting to create a single page application is that they allow us to create a more native-like/desktop-like/device-like application experience to the user. So the need was to create SPAs in a structured manner and this created a need for JavaScript frameworks and libraries that provided some structure to single page applications.
Currently there are quite a few Open Source JavaScript frameworks available that help us solve the problem of spaghetti code. These frameworks let us design our applications in a structured manner.
SPA
Single Page Application (SPA) , It is a concept not proper defination. 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 deliver the content faster. This model is result of evolutionary process. In beginning web page 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 user is consistently interuptted 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 hybrid model of web development. Major 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.
- Eg : Gmail, twitter.
So whats 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 and 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
Bulding up of SPA or complex UI interface will become extremely difficult if we use only JQuery. Javascript libraries are great but they donot provide any structure to code , maintainance is a nightmare and finally we would end in a code which would look something similar to first image. 

Backbone provides a proper structure to code, It follows kind of MVC pattern on client side and make the code modular.
With use of backbone entire communication with server can be done through RESTful API. Now a days browser are not the only client various mobile devices, tablets etc. A web site need to be compatible in all of these devices. Backbone make it pretty easy for developer to build such application and maintainance 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 need to be famaliar 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 - Its a library that provides functional programming support for javascript. Backbone provides many function for manipulating collection.
- JQuery/Zepto - All of DOM manipulation is done using JQuery , also all of the ajax call are made from this. Zepto is an JQuery alternative.
What will Backbone Provide
Model: Every application need some way of organizing their data structures. Backbone will provide us with the possibility of creating Models to manage all our entities. Backbone models by default provide the ways to persist themselves. The persistence can be on a localStorage or even on a server via a restful API. These models also provide ways to validate the data in the model before persisting it.
Collections: Collections are simply a group of models together. Backbone also provide the possibility of creating the ordered set of models i.e. collections.
Views: The major problem in JavaScript applications is to handle the UI elements on views. listening to their events and changing their values based on the data received. Backbone ease up this problem by providing an abstraction over the HTML elements i.e. views. Backbone view are like observers on some HTML. We can define the HTML and associate with a view. The view will then take care of handing the events of these HTML elements and populating and rendering these views based on data. The HTML is totally separate from the view object. It can be associated with the view object either directly or via some templating engine(hang on tight, we will get to see all these in action in due course of time).
Routers: Even though we want to create a single page web application, requirements might dictate the need of copying, bookmarking the URLs. So for a single page application, if we want the URL to determine the view/views to be rendered, routers are very helpful. routers will look at the requested URL and then execute code based on the requested URL and then render the view to the user.
Backbone provides set of tools for introducing structure into client-side apps.

Models - It provide 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 its not conern the way in which view is rendered.
var Person = Backbone.Model.extend({
initialize : function(){
console.log("Welcome to learning of backbone");
}
});
var p = new Person();
Collection - Collection are simply ordered group of models. They fire from model they contains also event of their own. Collection depend upon models.
<span style="font-size: 9pt;">var PersonList = Backbone.Collection.extend({
</span><span style="font-size: 9pt;"> model : Person
});
var list = new PersonList();</span>
View : View interacts with DOM, It handles events from model ,collection and DOM . It basically used to show whats the model data looks like along with templates used like underscore.js. Whenever user interacts with element , any changes made is being handled by controller and not view.
var PersonView = Backbone.View.extend({
collection : list,
initialize : function() {
console.log("An initilize 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 eg :
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();
});
Last but the not least
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 very strong javascript library which leaves us with a code that is maintainable in long run.
Happy Coding !!!
0 comments:
Post a Comment