adams.co.tt

Backbone.js - Models and Views

8th May 2011

What is backbone?

Backbone.js is a JavaScript framework which brings Model View Controller semantics to your JavaScript application. These semantics allow a rich JavaScript client application to be broken up in meaningful ways. DOM manipulation is separated from business logic by the views and models respectively. Controllers can be used to switch between ‘pages’ within your application.

Models and collections

Backbone provides model and collection classes. For example consider the following:

app.models.Article = Backbone.Model.extend({
  publishedTime : function () {
    return new Date(this.get('publishedDate')).toLocaleTimeString();
  }
});

Here we have a very simple Article class. You’ll notice we have not declared any attributes on this class. This is because backbone models gain their attribute structure from the data used to hydrate them.

Here we have a collection class:

app.models.ArticleList = Backbone.Collection.extend({
  url : '/articles',
  model : app.models.Article
});

As you can see, again the collection class is very anaemic. Both models and collections can be passed to views for rendering, and generate events. In this example the Article list maps to a url which returns JSON in the form:

[ 
  { 
    "id" : 1000,
    "body" : "Bar",
    "publishedDate" : "Mon May 02 2011 16:00:00 GMT+1000 (EST)",
    "title" : "Foo"
  },
  { 
    "id" : 2000,
    "body" : "Bam",
    "publishedDate" : "Fri May 06 2011 15:30:00 GMT+1000 (EST)",
    "title" : "Baz"
  }
]

The object list described here is what provides the models with their structure.

Views

Backbone provides a single view class from which we can extend:

app.views.ArticleListView = Backbone.View.extend({
  render : function () {
    var renderedArticles = _.map(this.collection.models, function (article) {
      return new app.views.ArticleView({model : article}).render().el;
    })
    $(this.el).html(renderedArticles);
    $('#container').html(this.el);
    return this;
  }
});

app.views.ArticleView = Backbone.View.extend({
  render : function () {
    var out = '<h1>' + this.model.get('title') + '</h1>';
    out += '<p>' + this.model.publishedTime() + '</p>';
    out += '<p>' + this.model.get('body') + '</p>';
    $(this.el).html(out);
    return this;
  }
});

Here we see views which can display the article list. The ArticleListView delegates to the ArticleView for rendering of individual elements of the collection. In this example we’re generating the HTML inline, however as your application grows, it’s most likely that you’ll want to extract this to some form of templating system.

The Application

Up until now we’ve only seen models, collections and views on their own. Now we can see how a very basic Backbone.js application hangs together. Here we declare the namespaces, the init function and register it to run on document ready.

var app = {
  models : {},
  views : {},
  init : function () {
    var articleList = new app.models.ArticleList();
    articleList.fetch({success : function () {
      var view = new app.views.ArticleListView({
        collection : articleList
      });
      view.render();
    }});
  }
};

$(document).ready(app.init);

And here we have an extremely basic Backbone.js application. You’ll notice that we have not yet leveraged any events or controllers. In my next post we’ll go over how to use these features to create an application to allow rich user interaction.

blog comments powered by Disqus