Get cracking with Backbone

For years developers have been taking advantage of PHP frameworks like CakePHP, CodeIgniter and even Ruby frameworks based on the MVC pattern. But if you think about it, there haven’t been a lot of JavaScript frameworks to help us out in the same way.

Perhaps it’s because JavaScript is often looked down on by ‘real’ programmers, but JavaScript frameworks have always lagged behind a little. Backbone changed that, and as you’ll see in this introduction, it uses the MVC pattern to separate JavaScript code and help us create structured applications. In effect, it delivers the MVC pattern to front-end development.

 

What is Backbone?

Backbone is a lightweight JavaScript library from the same creator as CoffeeScript. But don’t let the fact that it’s a library make you confuse it with jQuery, Backbone is leagues away from jQuery when it comes to functionality. Backbone doesn’t handle DOM elements, which is why many developers use it hand in hand with jQuery; Backbone organizing structure and jQuery manipulating the DOM.

What Backbone does really well is supply structure to your JavaScript applications, and because it works with JSON it’s simple to insert into almost any front-end templating system.

 

The MVC pattern in Backbone

MVC stands for Models, Views and Collections; and in Backbone, with also have Routers.

Models

In Backbone a model represents and entity, so for example, if we are dealing with users, each user would be a Model; it’s like a row in a database.

To create a simple model using Backbone we’d type:

var user = Backbone.Model.extend({});

That code is technically correct but that Model wouldn’t have any functionality, so we need to add something for this Model to do when it is instantiated and to do that, we’d use slightly more complex code:

User = Backbone.Model.extend({
    initialize: function(){
        alert('Welcome to WebdesignerDepot');
    },
    defaults: {
        name: 'John Doe',
        age:30,
    }
});
var user = new User;

In the above code, the initialize function will be triggered everytime we create a new instance of this model, after initialize all we’ve done is add some defaults in case no data is passed in for the Model. With that done, to create an instance of the Model we’d use code like:

var dave = new User({name:'Dave Smith', age:25});

To retrieve an attribute of a certain instance, we’d use:

var name = dave.get('name');

And to change an attribute we’d use:

dave.set({age:31});

This is the basics of how Models work in Backbone, there’s a lot more they can achieve but hopefully you can see the potential for structuring code already.

Collections

Remember I said that a model was like a user? Well, following that analogy a Collection is all the users we have. Collections are in essence sets of Models, and since we already have our user Model, we’ll build a collection from there:

var Users = Backbone.Collection.extend({
    model: User
});

Currently this Collection is empty, but it’s simple to create some users and add them to the collection:

var barney = new User({ name: 'Barney Stinson', age: 30});
var ted = new User({ name: 'Ted Mosby', age:32});
var lily = new User({ name: 'Lily Aldrin', age: 29});

var himym = new Users([barney, ted, lily]);

Now, if we console.log himym.models we’ll get the values from barney, ted and lily.

Views

Views are associated with a part of the DOM, they are designed to be tied to the Models that are essentially the data of the application and they serve to present this data to the end user.

Creating a view is simple:

UserView = Backbone.View.extend({
    tagName: 'div',
    className: 'user',
    render: function(){}
});

This is the basic structure of a view. The tagName is the element that will be used to wrap the view, the class is set using the className and lastly we add a render function, although in this last case the function was empty. It’s the render function that we use to add to the stage, like so:

UserView = Backbone.View.extend({
    tagName: 'div',
    className: 'user',
    render: function(){
        this.el.innerHTML = this.model.get('age');
    }
});

The el element in the render function refers to the wrapper we created and using the innerHTML function we placed the user’s age inside the div.

This example hasn’t used any templating system, but if you want to you can take advantage of Underscore.js that ships with Backbone.

We can also listen to events by attaching an event listener to our view and in this example we’ll create a simple click listener for our div (this code goes immediately after our render function):

events:{
    'click.user': 'divClicked'
},
divClicked: function(event){
    alert('You clicked the div');
}

Routers

Backbone Routers are used for routing the URLs in the application when using hashtags (#). To define a router you should always add at least one route and at least a function that will run when the desired URL is reached, like so:

var appRouter = Backbone.Router.extend({
    routes:{
        'user': 'userRoute'
    },
    userRoute: function() {
        // the code to run when http://example.com/#user
    }
});
Backbone.history.start();

This is an extremely simple router that will perform an action when the /#user hash is reached. The Backbone.history.start() method call asks Backbone to monitor the hashtags so that the various states of the site are bookmarkable and can be navigated with the browser.

 

Conclusion

This article only covers the very basics of Backbone, which can be used to build structured applications in JavaScript. I’d advise you to check out the templating system for use in conjunction with Backbone to see the full potential of this library. I hope that this brief introductions has shown you how useful MVC can be on the front-end.

Have you built applications with Backbone? What kinds of application would you like to build? Let us know in the comments.

Featured image/thumbnail, scaffolding image via Shutterstock.

0 shares
  • http://www.fadamakis.com/ Fotis Adamakis

    I recommend the plugin backbone.marionette which helps a lot with the views in large scale applications.

    • http://about.me/evanjacobs Evan Jacobs

      Agreed. Marionette is awesome.

    • m0j0_j0j0

      Marionette is very nifty. Its probably a good idea for the backbone (and MVC) beginner to get to the “gosh i keep doing the same thing over and over again” point before he/she abstracts out plenty that they don’t yet understand.

      Not exactly the same thing, but i jumped into javascript MVC with angularjs. Now that i stepped back to learn Backbone, I now truly understand what’s going on (and i can say i now understand those Pro/Con points people list when debating backbone vs someBrandNewMVC framework )

  • http://www.danielhanly.com Daniel Hanly

    So is Backbone something that you’d use as well as CakePHP or other PHP frameworks, or instead of?

    • http://about.me/evanjacobs Evan Jacobs

      You could use both together, sure. Backbone is meant for organization of front-end code, where CakePHP organizes server-side PHP code.

    • m0j0_j0j0

      Remember, Backbone is just an opinionated way of ARRANGING your javascript for your web app. Its still just javascript. So yes, you can use it with CakePHP.

      Although If you are using Backbone (because you are building a javascript-heavy one-page web app), i’d recommend a micro framework like SLIM php for your backend since backend work has been reduced to retrieving data.

  • http://www.colorexpertsbd.com/ Jenifer Jeny

    You promote plenty creative idea with most easiest way, plenty excellent creation of your user model, perceive it little critical.

  • qgustavor

    As I never was a, at least good, PHP programmer, so I ask: I seen it a lot on applications like Grooveshark or Wolfram|Alpha, but how MVC can help me?
    MVC is good only when there’s tabular data, like a list of musics, users or math results, or there’s another uses?

    • http://about.me/evanjacobs Evan Jacobs

      No you’re right, it’s mostly meant for managing structured data. If you’re not dealing with that, you probably don’t need the overhead of an MVC framework.

  • jared_stephens

    Great tutorial. I have used Backbone a bit (as well as AngularJS, which is similar), and I have to say this helped clear up a lot of things in my mind about it. The learning curve can be quite steep for someone who is not a deep javascript developer.

    • http://about.me/evanjacobs Evan Jacobs

      Most definitely. It took me a good while to really wrap my head around Backbone. How do you like Angular? I’ve heard it’s convenient since they provide abstraction for almost everything.

      • jared_stephens

        The abstraction was nice, and getting started straight out of the gate was definitely easier in Angular. But there is just not enough documentation and support out there to really take it far for someone who is kind of a lightweight developer (like myself). Plus, IE8 support for some of the cool stuff I wanted to do just wasn’t there, and I had to support IE8 at the time.

  • http://about.me/evanjacobs Evan Jacobs

    MVC stands for Model, View, Controller. It advocates the separation of data, presentation and logic to keep applications less spaghetti-like and offer benefits like automatic viewmodel updating. Most is possible the old way, of course – but code is a lot cleaner and more maintainable with a MVC pattern.

  • Fabian Rigassi

    If SEO is important I recommend rendering the page first with whatever server-side language you use. At least that’s what I’m doing right now as I’m trying Backbone.

    You can then still attach a Backbone View to an existing element with the “el” property.

    • http://about.me/evanjacobs Evan Jacobs

      Search engines can parse Javascript.

  • jeb

    though i have heard about frameworks all throughout my working experience and have studied some of them – zend and codeigniter, i have never really got into using one. when i start from scratch, i end up segregating my own functions, displays and logic. I just feel like it is easier to do the my-way or maybe i just don’t realize how it can help. to post a question, does it matter a lot to use a framework? thanks, Sara for the tutes.

    • http://about.me/evanjacobs Evan Jacobs

      Do whatever makes sense for your coding style. MVC enforces a specific structure that may not be needed for the complexity (or simplicity?) of your project.

      It’s like the procedural vs OO coding debate – it doesn’t really matter in the end, they both produce working code.

  • Augustine Joseph

    Thanks its a good tutorial for me to start the backbone.js

    thanks
    Joseph

  • http://artisticbird.com/ Anurag Saxena

    thanks for the article, can you please explain more about the backbone js, because i just new in it.