Skip to main content

Client side MVC with backbonejs - a simple example

Some developers do not pay much attention about the structure of the client side code in their web applications, and the way they organize the code may end up in a tangled pile of JavaScript codes which is less readable and difficult to maintain. Backbonejs is a framework for web front ends which solve these issue. You can build web applications with rich front ends with backbonjs and connects those all to your existing APIs over RESTful JSON interfaces.

In this post, I am trying to demonstrate how to build a client side MVC application with backbonejs, as simple as possible. The application is a list, which you can add and remove items. This is a very simplified version of the TodoMVC at, please proceed to the references at the end for more details.

Source code of this example : 

Application includes a model for individual list item, a collection to store list items, views/controllers to display, create, and delete items.

1. Index File

First we create an index file to hold all the html needed for the application, and inside this file we can load the libraries, basic application dependencies and application specific files.

<!doctype html>
<html lang="en" data-framework="backbonejs">
        <title>Backbonejs Simple MVC Example</title>

        <!-- The List -->
        <section id="list-section">
            <header id="header">
                <h1>The List</h1>
                <input id="new-item" placeholder="Type Here" autofocus>
            <section id="main">
                <ul id="items-list"></ul>

        <!-- The micro template for a single item -->
        <script type="text/template" id="item-template">
            <div class="view">
                <label><%- title %></label>
                <a href="#" class="destroy">X</a>

        <!-- Libraries -->
        <script src="lib/jquery.js"></script>
        <script src="lib/underscore.js"></script>
        <script src="lib/backbone.js"></script>
        <script src="lib/backbone.localStorage.js"></script>
        <!-- MVC -->
        <script src="js/models/item.js"></script>
        <script src="js/collections/list.js"></script>
        <script src="js/views/item-view.js"></script>
        <script src="js/views/list-view.js"></script>
        <script src="js/app.js"></script>

First section inside the body is the markups for the list which includes the heading, a text box to type list titles, and the empty list. When you type something in the text box and press enter the text should go to the list as an Item.

Next is the micro template for a single list item, in this application, template utility of underscorejs has been used to handle the templates. But you can use other JavaScript templating systems as well (Ex: handlebars).

Next section includes underscore frame work and other libraries (jQuery, underscorejs, and backbone local storage). Here, underscorejs is the only hard dependency of backbonejs.

Last section includes the application specific codes which we are going to discuss in the rest of this post.

2. Model (js/models/item.js)

/*global Backbone */
var app = app || {};

(function () {
 'use strict';

 app.Item = Backbone.Model.extend({

  // Default attributes
  defaults: {
   title: ''

This is the model for a single list item, with the only default attribute "title".

3. Collection (js/collections/list.js)

/*global Backbone */
var app = app || {};

(function () {
    'use strict';

    var List = Backbone.Collection.extend({

        // Reference to this collection's model
        model: app.Item,

        // Save all the items under the `"items"` namespace
        localStorage: new Backbone.LocalStorage('items-backbone'),

        // Next order number for new items
        nextOrder: function () {
            if (!this.length) {
                return 1;
            return this.last().get('order') + 1;

        // Items are sorted by their original insertion order
        comparator: function (item) {
            return item.get('order');

    // Create our global collection of **Items**.
    app.list = new List();

This collection groups the list items. Here we define the local storage namespace to store data, a function to get next order when creating a new item, and a comparator function to sort items.

4. List View (js/views/list-view.js)

var app = app || {};

(function ($) {
    'use strict';

    app.AppView = Backbone.View.extend({

        el: '#list-section',

        // Create New Items
        events: {
            'keypress #new-item': 'createOnEnter'

        // Bind to the relevant events at intialization 
        initialize: function () {

            this.$input = this.$('#new-item');
            this.$list = $('#items-list');

            this.listenTo(app.list, 'add', this.addOne);
            this.listenTo(app.list, 'reset', this.addAll);

            //{reset: true} - To suppresses 'add' events for intial loading  
            app.list.fetch({reset: true});

        render: function () {


        // Add a single list item
        addOne: function (item) {
            var view = new app.ItemView({ model: item });

        // Add all items in the list
        addAll: function () {
            app.list.each(this.addOne, this);

        // Get the list of attributes for a new item
        getAttributes: function () {
            return {
                title: this.$input.val().trim(),
                order: app.list.nextOrder()

        // Create a new item when pressing the enter key in text box
        createOnEnter: function (e) {

            if (e.which !== ENTER_KEY || !this.$input.val().trim()) {



In backbonejs, the view is the real controller, and the actual views are the html templates. Views, and templates together performs the job of controllers and views as in server side MVC application. There for, main application logic goes inside these views.

Most important thing to notice here is to how the view handles the events and listen to the changes of data and models. The function "createOnEnter" is called when the key down event occurs, and the view listens to the "add" event to update the list by calling "addOne" function when a new model(item) is added to the collection(list).

5. Item View (js/views/item-view.js)

var app = app || {};

(function ($) {
    'use strict';

    app.ItemView = Backbone.View.extend({

        // Tag name for the current view
        tagName:  'li',

        // Template for a single item
        template: _.template($('#item-template').html()),

        // Events specific to an item
        events: {
            'click .destroy': 'clear'

        // Listens for changes to item model
        initialize: function () {
            this.listenTo(this.model, 'destroy', this.remove);

        // Render the item
        render: function () {

            return this;

        // Remove the item from storage and UI
        clear: function () {

This is the view for a single list item. When rendering, it uses the micro template and the data from a model to render the new list item. When the click event occurs to delete an item, the "clear" function is called to remove the item from both UI and Storage.

6. App.js (js/app.js)

var app = app || {};
var ENTER_KEY = 13;
var ESC_KEY = 27;

$(function () {
    'use strict';

    new app.AppView();

Finally, the list view should be instantiated when the page is loaded. In addition to that, some global variables we need in the application have been defined here.

Please go through the references given below for leaning backbonejs in detail.

Developing Backbone.js Applications by Addy Osmani
Backbonejs TodoMVC


Popular posts from this blog

Common Characteristics of Enterprise Applications

Last week, I was conducting a tech talk about “Architectural Patterns of Enterprise Applications” with our team. The discussion was mainly based on Marin Fowler's famous book “Patterns of Enterprise Application Architecture”. So, I thought, it's good to write something about that in my Blog. Given below are few common characteristics of Enterprise Applications. If any software product has the following characteristics, we can identify it as an Enterprise Application. These ware originally documented by “Martin Fowler”, in his book “Patterns of Enterprise Application Architecture”. Persistent Data - Enterprise applications usually involve persistent data. The data is persistent because it needs to be around between multiple runs of the program—indeed, it usually needs to persist for several years. Also during this time there will be many changes in the programs that use it. Lot of Data - There's usually a lot of data, a moderate system will have over 1 GB of data organ

How to avoid those little issues one can get when creating new projects with Zend Framwork...

CSS styles my not apply to the templates : Some times this happens when you haven't created a virtual host for the application. After the virtual host is created styles will apply properly, or just use some url helper like "baseUrl" when linking the style sheets to the templates. Error messages when using the commands like "zf enable layout", "zf create db-table ....", "zf create model ...", "zf configure db-adapter", and "zf create action ...." etc... You may get error like "Action 'enable' is not a valid action", "Action 'configure' is not a valid action"......... etc... Reason for this may be, the Zend library is not in the include path. If so add the library path to the include path. Or check whether there are old libraries in any directories of include paths that conflicts with the new one. Check whether there is a one as a PEAR package. And check whether the "zf" c

How to create a waveform animation with HTML and JavaScript

Recently, for a pet project, I wanted to create an animation of a waveform based on the varying decibel level of the microphone input. I was thinking about a really simple way to accomplish this with SVG and JavaScript. Given below is the first sample code I did on the Codepen. You can change this code to use with any framework of your choice. For this sample code, I am using a random number as the microphone input. You can replace it with any other time based input. Code Pen : For this example, you need an HTML code snippet like the one given below. It’s just an SVG with a Polyline element inside.  <div style="text-align:center">   <svg height="150" width="400" id='svg'>     <polyline id="polyline-id" fill="none" stroke="#005c66" stroke-width="1" />   </svg> </div> And then the plain Javascript code to animate the polyline. You can