Hendra Nicholas I am a software engineer, consultant and CEO at 41studio currently living in West Java, Indonesia. My interests range from programming to sport. I am also interested in entrepreneurship, technology, and design.

Getting Started with Backbone.js

3 min read

Getting Started with Backbone.js

Backbone.js is a JavaScript framework, among many others, that is gaining special attention in the web development community because it’s ease of use and the structure that it provides to JavaScript applications.

Backbone is an incredibly small library for the amount of functionality and structure it gives you. One can’t easily summarize the benefits you will reap from using it. If you read through some of the beginner tutorials the benefits will soon become self evident and due to Backbone.js light nature you can incrementally include it in any current or future projects.

Backbone.js has hard dependency on Underscore.js and a soft dependency on jQuery. It’s composed by the following modules:

  • Views
  • Events
  • Models
  • Collections
  • Routers
[code language="HTML"]
 	<!-- ========= -->
 	<!-- Libraries -->
 	<!-- ========= -->
 	 	type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">

 	  type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js">

 	 	type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js">

 	  type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js">

1. Backbone’s Views

Backbone’s Views are the equivalent of ‘controllers’ on MVC frameworks (like Ruby on Rails). Backbone’s Views related to user events (clicks, pressed keys, types, etc.), render HTML views and templates, and interacts with models which contains the data of the application.

[code language="JavaScript"]
 		<!-- =============== -->
 		<!-- JavaScript code -->
 		<!-- =============== -->

 		<script type="text/javascript">

 		// <![CDATA[ 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 function to push content. Like the Hello World in this case.

 				this.$el.html("Hello World");


 		 var appView = new AppView();


2. Backbone’s Model

Models are the heart of every application. It contains the interactive data and the logic surrounding it, such as data validation, getters and setters, default values, data initialization, conversions and so on. For our example, we are going to create a model called Todo, which will store a string of text (title) and whether the task has been completed or not.

[code language="JavaScript"]
//-------------- // Models //--------------
	app.Todo = Backbone.Model.extend({ default: { title: ''; completed: false } });

3. Backbone’s Collection

As its name indicates, collections are ordered sets of models, where you can get and set models in the collection, listen for events when any element in the collection changes, and fetching for model’s data from the server.

[code language="JavaScript"]
//-------------- // Collections //--------------
	app.TodoList = Backbone.Collection.extend{( model:
	app.Todo, localStorage: new Store("backbone-todo") }); // instance of the Collection
	app.todolist = new app.TodoList();

Collections allows to save data (in database, file, memory), and it requires a reference to it. Therefore, you need to specify the url parameter with a relative url, where the model’s resource would be located on the server. Otherwise, you will get errors like:

A "url" property or function must be specified.
PS: for now we're going to use LocalStorage.

4.Basic Properties

There are 4 basic properties in a view: el, initialize, render, and events.

A. View.el

Every view needs to reference a DOM at all times. Therefore, the view will inject content into this element. This is the el property. this.el is created from view’s el,tagName, className, idor attributes properties. If none of these are specified, then this.el is an empty div. The view.$el it’s a cached jQuery object of the view’s element (view.el).

B. Initialize / Construtor

Here you have the option to pass parameters that will be attached to a model, collection or view.el.

C. Render

This function injects the markup into the elements. Not all views require having a render function, as you are going to see in the sample code, they can call other view’s render functions.

D. Delegated Events

Event are written in the following format :


i.e :

events: ('keypress #new-todo': 'createTodoOnEnter'}

in jQuery it would be something like:


5. Backbone’s Events

This module can be mixed with any object and give it the pub/sub (observer patter) behavior. Events provides a couple of methods from which we are going to discuss: on, off and trigger. (If this you are familiar with then in jQuery, they will work the same way + some nice built-in features).

object.on(event, callback, [context])

Also called bind. It binds an object to an event and a callback. When that event it’s triggered it executes the callback.

todoList.on('add', this.addAll, this);

Everytime a new item is added to a Backbone.Collection the event add is triggered. In the example above, after the event is triggered the todoList’s callback addAll() is executed and the current object is passed with this as a context.

Written by: Fitria Rahmaani – Web Developer at 41studio

Hendra Nicholas I am a software engineer, consultant and CEO at 41studio currently living in West Java, Indonesia. My interests range from programming to sport. I am also interested in entrepreneurship, technology, and design.