Basic Backbone

Javascript has been around for years now.  Its one technology that just does not seem to be going away any time soon.  Not only that, but it has evolved tremendously since its inception.  Within the past few years various MVC javascript frameworks have been coming onto the scene, making it easier and easier for developers to organize their code.  While they have some similarities, a javascript MVC framework is drastically different then a backend framework such as Ruby on Rails.  Another important note, is that these frameworks are not meant to replace a library such as jquery.  Rather, they work in conjunction.

One such javascript MVC framework that I have been studying as of late is backbone.js.

Backbone has four major classes:

  • Model – A model is a representation of data.  This could be a record from a database, a picture, or a hyperlink.  There is no concrete rule as to where the data would necessarily need to come from.
  • Collection – A collection is simply a group of models.
  • View – A view is responsible for representing model to the user as well as listening for any changes within the DOM.
  • Controller – A controller (which I will not be covering extensively in this post) allows you to create bookmarkable states using “hashbangs”.

With this basic knowledge, lets go ahead and create a very small application with backbone.  This app will generate a very simple linked menu.

Lets start with the following basic HTML page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Backbone.js Web App</title>
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>
        <div id = "menu"></div>
       
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="js/json2.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
        <script src="js/app.js"></script>
    </body>
</html>

This is nothing more then a basic html file.  We are including a few javascript files in here:

  1. JQuery: pretty self explanitory if you’ve used javascript before.
  2. json2: allows us to parse to a json object or “stringify” a json object.
  3. underscore: this is a templating system for backbone.  There are other options that could be used.  More on this later.
  4. backbone.min.js: The source for backbone.js.
  5. app.js: this is where we will be doing most of the work.

 

If you haven’t already, create a new file called app.js in your “js” folder.

The first step is to create our menuItem model.

1
2
3
4
5
6
7
8
9
10
11
12
(function ($) {

    //create menu item object
    var menuItem = Backbone.Model.extend({
        defaults: {
            title: "menu item",
            url: "http://www.mysite.com",
            item_id: "menu-item"
        }
    });

} (jQuery));

The class menuItem simply extends the backbone model class (Backbone.Model) and we’ll be adding defaults (if nothing is specified). The model as you can see specifies all of the attributes for the menuItem data class.

Next, we create menuItem collection.

1
2
3
4
//create a collection object
    var Menu = Backbone.Collection.extend({
        model: menuItem
    });

This block of code simple declares our collection class. We are extending backbone’s “Collection” object and specifying that the collection of models for Menu is “menuItem”.

The next step is to create a view for a menu item. This view will listen for changes, and specify various layout attributes such as the HTML tag where this model will reside.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//create the view for a menu item
    var menuItemView = Backbone.View.extend({
        tagName: 'span',

        className: 'menu-item',
        id: function() { return this.model.get('item_id') },
        template: _.template( $("#menuitem_template").html()),

        initialize: function() {
            this.render();
           
        },

        render: function() {
            this.$el.html( this.template(this.model.toJSON()));
            return this;
        }

    });

Each menuItem, will be wrapped in a “span” tag(see tagName attribute), with an html class called “menu-item(className attribute)”. We are also specifying that the span will have an id(id attribute) equal to the item_id parameter. The next line specifies our template location within the HTML file. More on this a little bit later.

If you are not familiar with Javascript objects, the initialize function is something that is universal to all objects. When a new object is instantiated, the “initialize” method is automatically run. As you can see, all the initialize function does in this case is run the render method.

The render method takes our model that is passed in, and puts it into html form. You’ll notice we use a method this.$el. This method takes our object and turns it into a cached jquery object that can then be rendered in your view. As you can see we are passing in “this.template”, which contains a JSON parsing of our model, which then returns back our html view. This part can be a little confusing.

Now is an appropriate time to show how the templating system works. In this case, we are using underscore. However, there are several templating modules that can be used. Other alternatives include: Handlebars, Mustache.js, and haml.js among others. I will not cover these today.

If you are familiar with erb on rails, the underscore syntax is similar. The following must be added to our html page between #menu div:

1
2
3
<script id="menuitem_template" type="text/template">
       <a href = <%= url %> > <%= title %></a>
</script>

You will notice that in the script tag we have an id of “menuitem_template”. This is how backbone knows where to put our view data. In the template attribute of our menuItem view we have the line of code which identifies the template to put our model data in:

1
template: _.template( $("#menuitem_template").html())

Backbone now knows to put the model’s title attribute where “<%= title %>” is and its url attribute where “<%= url %>” is.

Now that our view is set, we will create a new collection, and create a view.

The code to create the collection is pretty self explanatory.

1
2
3
4
5
6
7
8
//create a collection of items
    var menu = new Menu([
       
        { title: "Home", url: "http://www.mysite.com", item_id: "home" },
        { title: "About", url: "http://www.mysite.com/about", item_id: "about" },
        { title: "Links", url: "http://www.mysite.com/links", item_id: "links"}
       
    ]);

This is simply a new “Menu” object, which was prototyped above.

The last item that we have to deal with is the view for our collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var menuView = Backbone.View.extend({
        el: $("#menu"),
       
        initialize: function() {
            this.render();
        },

        render: function() {
            var menuItem;

            _.each(this.collection.models, function(item){
                this.renderMenuItem(item);
            }, this);
               
        },

        renderMenuItem: function (item) {
            var menuItem = new menuItemView({ model: item });
            this.$el.append(menuItem.render().el);
       
        }
    });

The first thing that you will notice is that we specify the element. We are attaching this view to the

with the id of “menu”. The initialize function is run, which basically runs the render method.

The render method will simply loop through the entire collection, and render the view (menuItemView) for each model within the collection. The process of rendering is abstracted to the method: “renderMenuItem”. This process simply appends the menuItemView to the menuView element, which as we know is the div with an id of “menu”.

Finally now that all of our prototypes and objects have been created, all that is left t. do is create an instance of our menu view:

1
var menuView = new menuView({ collection: menu });

That’s it. If you load up the html page, you will simply see a list of the three menu items created in our collection. That’s it for today! Please let me know if you have any questions.

Leave a Reply

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