Skip to main content

Backbone.js - An Introduction

Backbone.js is a lightweight JavaScript library that adds structure to your client-side code. Developers commonly use libraries like Backbone.js to create single-page applications (SPAs). 

What is a Single-Page-Application?

A single page Web App is a website that attempts to recreate the experience of a native desktop or mobile application. On a Single Page Web App you are less likely to see page refreshes, the browser navigation within the app is often overridden and there will usually be some offline capabilities. To a user their interaction with a Single Page Web App will be almost identical to how they interact with a full native application.

Backbone has many advantages over other js frameworks. Backbone is mature, popular, and has a number  of plugins and extensions available that build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and LinkedIn.

Backbone organizes its whole code under the famous pattern called MVC (Model-View-Controll). It has thee parts and can be defined as follows:

  • Models represent the domain-specific knowledge and data in an application. Models can notify observers when their state changes.
  • Views typically constitute the user interface in an application. They observe Models, but don’t directly communicate with them.
  • Controllers handle input (e.g., clicks, user actions) and update Models.
Thus, in an MVC application, user input is acted upon by Controllers which update Models. Views observe Models and update the user interface when changes occur.

MVC pattern in Backborn.js
First let us talk about Models in Backbone.js. A model is a simple representation of the data of your application. To create a new model, one must first extend from Backbone.Model to create a custom model that will be used to create an individual instance of your Model object.

var Todo = Backbone.Model.extend({
  initialize: function(){
      console.log('This model has been initialized.');
  }
});

var myTodo = new Todo();
// Logs: This model has been initialized.


Next we will discuss Views. To create a view we extend from Backbone.View similar to how we created the Model. In Backbone.js, a view is responsible for rendering out the data that is housed in your application models. Usually this will be done using a HTML templating library to create clean reusable markup. Backbone.js uses underscore templates for this purpose.

var TodoView = Backbone.View.extend({

  tagName:  'li',

  // Cache the template function for a single item.
  todoTpl: _.template( "An example template" ),

  events: {
    'dblclick label': 'edit',
    'keypress .edit': 'updateOnEnter',
    'blur .edit':   'close'
  },

  // Re-render the titles of the todo item.
  render: function() {
    this.$el.html( this.todoTpl( this.model.toJSON() ) );
    this.input = this.$('.edit');
    return this;
  },

  edit: function() {
    // executed when todo label is double clicked
  },

  close: function() {
    // executed when todo loses focus
  },

  updateOnEnter: function( e ) {
    // executed on each keypress when in todo edit mode,
    // but we'll wait for enter to get in action
  }
});

var todoView = new TodoView();

// log reference to a DOM element that corresponds to the view instance
console.log(todoView.el); // logs <li></li>

Thirdly we will talk about Collections. Collections are basically groupings of models. Collections will usually define where the RESTful url is to GET and POST our data from and what the model type is that they contain. This common behavior is done by overriding the url attribute and the model attribute when extending from Backbone.Collection.

var Todo = Backbone.Model.extend({
  defaults: {
    title: '',
    completed: false
  }
});

var TodosCollection = Backbone.Collection.extend({
  model: Todo
});

var myTodo = new Todo({title:'Read the whole book', id: 2});

// pass array of models on collection instantiation
var todos = new TodosCollection([myTodo]);
console.log("Collection size: " + todos.length); // Collection size: 1


Finally there are routers which extend from Backbone.Router. A router's responsibility is to direct specific requests for urls to certain routes within the application and to keep track of a history that will override the base behavior of the navigation of the browser. This behavior allows users to more naturally navigate through the site like navigate application rather than a series of html pages. Backbone.Router uses the # symbol in the url to prevent different pages from loading when navigating via the browser's navigation buttons. The best practice for building an app with a single router is to actually just create an instance right when you extend from Backbone.Router.

var TodoRouter = Backbone.Router.extend({
  /* define the route and function maps for this router */
  routes: {
    "about" : "showAbout",
    "search/:query" : "searchTodos",
    "search/:query/p:page" : "searchTodos"
  },

  showAbout: function(){},

  searchTodos: function(query, page){
    var page_number = page || 1;
    console.log("Page number: " + page_number + " of the results for todos containing the word: " + query);
  }
});

var myTodoRouter = new TodoRouter();

This is the basic structure of a MVC pattern in Backborn.js. All applications are built upon this basic structure. To have detailed discussion about various commands used in Backborn.js and other clarifications, please refer the official Backborn.js site.

Comments

Popular posts from this blog

Elements of Programming in Scheme

A powerful programming language provides a framework to interpret our ideas of processes. It generally combines small procedures to complex ones. Usually there are three steps to accomplish this. primitive expressions , which represent the simplest entities the language is concerned with, means of combination , by which compound elements are built from simpler ones, and means of abstraction , by which compound elements can be named and manipulated as units. Some very basic ideas in manipulating with the data are given below. Expressions   A very simple expression is a number. Simple expressions are combined to form complex ones. For example:                   (+ 2  3  4) is an expression where + is the operation and 2,3,4 are the oparents. The expression can be made more complex by combining simple expressions as given below:              ...

Abstraction Using Higher Order Procedures

Procedures are, in effect, abstractions that describe compound operations on numbers independent of the particular numbers. Yet even in numerical processing we will be severely limited in our ability to create abstractions if we are restricted to procedures whose parameters must be numbers. Often the same programming pattern will be used with a number of different procedures. To express such patterns as concepts, we will need to construct procedures that can accept procedures as arguments or return procedures as values. Procedures as arguments Procedures are often used as the arguments of an another procedure. This provides a higher level of abstraction in programming. For example consider a procedure to find out the sum of squares of numbers between a range. The procedures inc and square are used as the arguments of the procedure sum, which is generalised as follows.                 (define (inc...