Backbone.js – Complete tutorial for beginners

What is Backbone.js?

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.

Introduction

The Evoluton of Web Application has been gradual over the years, starting from static html pages to dynamic pages developed using languages like PHP, PERL, Ruby etc. With the customer focus on UI(User Interface) & UX(User Experience) grew, the web applications became more and more dependant on Javascipt, jQuery libraries to do tasks such as validations etc. As time went on the dependant on Javascript libraries grew so much that now web application development is done mainly on the client side rather than client side. More focus has been given to the interface rather than functionality and this led to the creation of built-in libraries like jQuery UI and so on.

Then came the mobile revolution and everything that was until now built for 1000px scale was scrapped. Now the focus is on creating applications which runs same on all platforms and such applications came to be known as HTML5 applications with the introduction on HTML version 5. With this the application development side has seen a boom in the number of libraries created. The most used mobile frameworks includes jquerymobile, titanium appcelerator and Sencha.

This was not enough apparantly. The multi-page website creation which we are used to was replaced with single-page websites which focussed purely on User interface. The one draw-back of creating single page applications was the over-usage of javascripts and its libraries. Maintaining a large junk of javascript code was literally impossible and re-using only created more issues. Solution was simple.

Introduction of MVC architecture in javascript has been by far the greatest change that has occurred to Web application development. Numerous frameworks were introduced which made the concept of MVC or MV* javascript architecture in practise. Some of the frameworks which uses MVC/MV* architecture is listed below :

  • Backbone.js: Provides models with key-value binding and custom events, collections, and connects it all to your existing API over a RESTful JSON interface.
  • AngularJS: A toolset based on extending the HTML vocabulary for your application.
  • Ember.js: Provides template written in the Handlebars templating language, views, controllers, models and a router.
  • Knockout: Aims to simplify JavaScript UIs by applying the Model-View-View Model (MVVM) pattern.
  • Agility.js: Aims to let developers write maintainable and reusable browser code without the verbose or infrastructural overhead found in other MVC libraries.
  • CanJS: Focuses on striking a balance between size, ease of use, safety, speed and flexibility.
  • Spine: A lightweight framework that strives to have the most friendly documentation for any JavaScript framework available.
  • Maria: Based on the original MVC flavor as it was used in Smalltalk – aka “the Gang of Four MVC”.
  • ExtJS: Amongst other things offers plugin-free charting, and modern UI widgets.
  • Sammy.js: A small JavaScript framework developed to provide a basic structure for developing JavaScript applications.
  • Stapes.js: A tiny framework that aims to be easy to fit in an existing codebase, and because of its size it’s suitable for mobile development.
  • Epitome: Epitome is a MVC* (MVP) framework for MooTools.
  • soma.js: Tries help developers to write loosely-coupled applications to increase scalability and maintainability.
  • PlastronJS: MVC framework for Closure Library and Closure Compiler.
  • rAppid.js: Lets you encapsulate complexity into components which can be easy used like HTML elements in your application.
  • Serenade.js: Tries to follow the ideas of classical MVC than competing frameworks.
  • Kendo UI: Combines jQuery-based widgets, an MVVM framework, themes, templates, and more.

The javacript frameworks provide structure to organize the code and increase maintainability. Of the above listed frameoworks, Backbone is one of the most widely spread framework in its category. It has a vibrant community and it’s also being fully used in production for a considerable number of big companies like: Wal-Mart mobile, Groupon, Khan Academy, Pandora, WordPress, Foursquare etc.

Overview of Backbone.js

Backbone.js is composed of the following modules:

  • Models – Models are the heart of any Javascript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.
  • Collections – Collections are ordered sets of models. You can bind “change” events to be notified when any model in the collection has been modified, listen for “add” and “remove” events, fetch the collection from the server, and use a full suite of Underscore.js methods. Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection.
  • Routers – Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it’s now possible to use standard URLs (/page). Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don’t yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.
  • Views – Backbone views are almost more convention than they are code — they don’t determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view’s render function to the model’s “change” event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.
  • Events – Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.

Lets get started with coding.

Demo Tutorial 1 – Hello World!

Download the sample template file from here : https://github.com/roymj88/back-bone-basics/blob/master/template.html

Adding the Container :

<!--Container for loading the Application views -->
<div id="container">Loading...</div>
<!--Container for loading the Application views -->

Adding the View :

var AppView = Backbone.View.extend({
// el - stands for element. Every view has a element associate in with HTML
// content will be rendered.
	el: '#container',
// It's the first function called when this view it's instantiated.
initialize: function(){
	this.render();
},
// $el - it's a cached jQuery object (el), in which you can use jQuery functions
//       to push content. Like the Hello World in this case.
render: function(){
	this.$el.html("Hello World");
}
});

Run the sample code and now you can see it in action.

You can download the entire workout sample through : https://github.com/roymj88/back-bone-basics

I will be adding more demos in the coming days. Do leave a comment if you have any doubts/issues.

Leave a Reply

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