Skip to content

A very simple Backbone.js tutorial (not for the already familiar)

Backbone.js live Model View example

The following tutorial targets the developer who has heard a lot about Backbone.js but doesn’t quite know where to start. There are lots of resources and tutorials out there that already aim to help in this way but I’ve personally been left confused by many through my learning process.

Object Oriented

One of the things I love about Backbone.js is it’s object-oriented nature. You have a view, and a model. The view listens for changes and passes it back to the model, the model re-renders the view. Brilliant and simple. Coming from an Object Oriented PHP background this kind of syntax is particularly familiar to me.

// Example model
var ourModel = Backbone.Model.extend({
 
  // Constructor
  initialize : function() { 
 
    // Call method
    this.method(); 
  },
 
  // Method
  method : function() { 
 
    // Method does something
    console.log('method called');
  }
 
  // Methods...
});

Dependencies

Backbone.js depends on a couple of things to function correctly.

  • jQuery (The Backbone.js view method relies heavily on jQuery)
  • Underscore.js (a JavaScript toolbelt)

These assets need to be loaded in the correct order in the head of your HTML document. I’m just going to use the assets from CDNJS.com

<!DOCTYPE html>
<html>
<head>
<title>Example Backbone.js App</title>
<!-- Note jQuery > 2.0 does not support < IE9 -->
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.js"></script> 
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script> 
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script> 
 
</head>
<body></body>
</html>

A simple Backbone.js View

Our view is going to listen on a simple click event. It will pass the event data to the model, then the model will return the updated data to the view. When the event is triggered, it will log a message in the console.

Just after the dependencies are loaded before the end of the head tag we are going to add the following:

<script type="text/javascript">
// VIEW
var ourView = Backbone.View.extend({
 
    // Listen for click event
    events : {
        "click" : "clickHandler"
    }, 
 
    initialize : function() {
 
        // Bind click event
        this.on('click', this.clickHandler); 
    },
 
    // The view render
    render: function() {
        this.$el.html("<div id='square' />");
    },
 
    // The click handler
    clickHandler : function(event) {
 
        // Verify click is being handled
        console.log('click handled');
    }
});
 
// Initiate view
var view = new ourView();
 
// Append to view to document body
view.$el.appendTo(document.body);
 
// FIRE
view.render();
 
</script>

And we’re just going to create a default style for the square element that’s being created

<style type="text/css">
#square {
    position:absolute; /* Absolute Positioning gives us free roam */
    width:50px;
    height:50px;
    background:black; /* Default color */
}
</style>

The View contains a series of methods.

  • events : function() { } – contains the events we want to listen and it’s associated method inside the view. In this case, it calls the method clickHandler()
  • initialize : function() { } – anything that is here is fired as soon as the class is called. Here, when the class is initialised we have told it to listen for our click event. It binds our clickHandler() method to the event. this.on(‘click’, this.clickHandler);
  • render: function() { } – is the method we use to render the new element. In this case we’re creating the element to be rendered. this.$el.html(elem);
  • clickHandler : function() { } – is the function called when the click event is triggered. We are returning a message to the console.

We create a new object and store it in a variable

  • var view = new ourView();

In this case, I want to simple append the element to the document body. The element is stored inside $el.

  • view.$el.appendTo(document.body);

To finish off, we need to render our view which is the classes render() method.

  • view.render();

If this is correct then you should have a black square box that when clicked on returns the message ‘click handled’ to the console. The live example is shown here:
Backbone.js Simple View

A simple Backbone.js Model

Now let’s create a model that we want our view to interact with. Very simply we’re going to create the basis of our model and get our view to connect with it.

// MODEL
var ourModel = Backbone.Model.extend({
    initialize : function() {
 
        // Verify view is connected to model
        console.log('model initialized');
    }
});

For now this will just send a message to the console letting us know that the model has been connected correctly to our view. To connect it to our view we need to make sure that once our view is initialised that it calls our model.
Inside our view initialize() method

    initialize : function() {
 
        // Bind click event
        this.on('click', this.clickHandler); 
 
        // Incorporate our model
        this.model = new ourModel(); // <-- Add this 
    },

If this has been done correctly, when the view is initialized the message ‘model initialized’ should appear in the console. Here is the next stage of the live example.
Connecting a Model to our View

Now to make it do something

For this next example, I’m just going to change some things around since they are not necessary. Let’s strip the Model and View down to the following:

// MODEL
var ourModel = Backbone.Model.extend({
    initialize : function() {
 
        // Verify view is connected to model
        console.log('model initialized');
    },
 
    // Our move method
    move : function(elem,x,y) {
 
    }
});
 
// VIEW
var ourView = Backbone.View.extend({
 
    // Listen for click event
    events : {
        "click" : "clickHandler"
    }, 
 
    initialize : function() {
 
 
    },
 
    // The view render
    render: function() {
        this.$el.html("<div id='square' />");
    },
 
    // The click handler
    clickHandler : function(event, $el) {
 
        // Verify click is being handled
        console.log('click handled');
 
    }
});
 
// Initiate view
var view = new ourView();
 
// Append to view to document body
view.$el.appendTo(document.body);
 
// FIRE
view.render();

Notice I have removed the click event to the square, but I’m still rendering it. I have also added a method to the model named move(). We are going to listen for a click event inside the body wrapper and move the square to that position. Let’s just define the size of our wrapper as well using CSS.

body {
    border:1px solid black;
    width:500px;
    height:300px;
}
 
#square {
    position:absolute; /* Absolute Positioning gives us free roam */
    width:50px;
    height:50px;
    background:black; /* Default color */
}

The square element in all of this example has been absolutely positioned for this very reason – because now we can move this anywhere on the screen based on the offset of our mouse at the time the click event is fired.

Let’s add some code to our move(); method inside our Model.

    // Our move method
    move : function(elem,x,y) {
        $(elem).animate({
            'left':x,
            'top' :y
        },500);
    }

This may look self explanatory. Basically, this method requires 3 arguments. The element, the x position and the y position. We then use a bit of jQuery to animate the element to this position. This method is going to accept these arguments that are to be passed by the view. Let’s add that code now.

    // The click handler
    clickHandler : function(event) {
 
        // Verify click is being handled
        console.log('click handled');
 
        // Instantiate model
        this.model = new ourModel();
 
        this.model.move(square, event.pageX, event.pageY);
 
 
    }

We are instantiating the model inside our handler. The event part of the handler contains a lot of attributes associated to the event including the x and y position of the mouse at the time it has been triggered – so we’ll just pass these in.
WARNING: event.pageX and event.pageY properties are part of the CSS Object Model View and these are usually implemented in different ways across browsers, so don’t rely on this to be functional in every browser – instead you can write a new method to determine the offset of the mouse cursor.

Something interesting here. Notice that I have just passed ‘square’ as the element part of the argument without defining it anywhere in this code. Unbelievably because we have given this element an ID of square, JavaScript automatically creates a global variable for it which corresponds to the ID name of the element. So in this case, we can just pass square into that argument.

Now for the final bit. We need to make sure that the click event is binded to the body wrapper at the time the view is initialised.

    initialize : function() {
 
        // Bind click event to body
        $('body').on('click', this.clickHandler);
 
    },

And that is it. When you click inside the body wrapper the square should move there. The full code is here
Backbone.js live Model View example
If you have stumbled across this I would appreciate your feedback so feel free to get in touch.

About 

I run a small web development agency in Salisbury, UK. We provide both front-end/back end solutions and infrastructure management. My specific role is to identify the needs of our clients and providing an online solution that is easy to administer, secure, scalable and maintainable.

 

My agency website is white-fire.co.uk. Contact us if you need a consultant.

Published inJavaScript

Be First to Comment

Leave a Reply

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