Getting started with backbone.js

April 27, 2012

I want to build a client side application (one that runs in the browser), making use of data supplied from my server via json. This app will perform mathematical calculations on the data, and by doing this I move the load to the client, distributing it amongst all my users. I'm going to do this using backbone.js.

Here's a simple backbone.js example that fetches data via json and displays it in the browser.

Loading Scripts

backbone.js depends on underscore.js, so we'll need to include both these libraries. CDNJS provides a content delivery network for many javascript projects, so we'll use that for now:

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/underscore-min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>

Template

We are using underscore.js templates to render things. Here's we're defining a template for how to show a band in HTML, i.e. it's the name of the band in an li tag.

<script type="text/template" id="bandlist_template">
  <li><%= band_name %></li>
</script>

JavaScript

Next we have some Javascript. All of this is within a <script> tag, and in the jquery $(function(){ call.

<script type="text/javascript">
$(function(){

First we create a band model. We're not going to define any fields, as these will be derived from json later.

var Band = Backbone.Model.extend();

Next we create a collection of bands, and define the URL where you can GET to obtain a list of bands.

var BandList = Backbone.Collection.extend({
  model: Band,
  url: '/bands/data/'
});

We now define a way for the band list to be displayed. The template attribute references the template we set up in the html earlier, by id. The render function iterates around all the bands and renders the template for each band, adding the template html to an internal div.

var BandsView = Backbone.View.extend({
  template: _.template($('#bandlist_template').html()),
  render: function(eventName) {
    _.each(this.model.models, function(band){
      var lBandName = band.attributes['band_name'];
      var lTemplate = this.template(band.toJSON());

      $(this.el).append(lTemplate);
    }, this);
    return this;
  }
});

We now create a BandList instance.

var lBands = new BandList;

And finally define an AppView object

var AppView = Backbone.View.extend({
  el: "body",

  render: function(){
    var lBandsView = new BandsView({model:lBands});
    var lHtml = lBandsView.render().el;
    $('#bands').html(lHtml);
  },

  initialize: function(){
    var lOptions = {};
    lOptions.success = this.render;
    lBands.fetch(lOptions);
  }
});

The initialize function here fetches the list of bands via JSON, and then does a callback to the render method in order to display them on the page.

We need to create an AppView instance to kick off the application, and then we finish the jQuery function call

  var App = new AppView;
});
</script>

HTML

Our HTML is a single div, which we populate with the rendered band list template.

<ol id="bands">
</ol>

JSON

The JSON returned from the /bands/data/ url is in the following format:

[
  {
    "id": "149",
    "band_name": "Armthorpe Elmfield",
    "section": "Fourth"
  },
  {
    "id": "127",
    "band_name": "Barnsley Chronicle",
    "section": "Second"
  },
  {
    "id": "155",
    "band_name": "Barnsley Metropolitan Band",
    "section": "Fourth"
  }
]

References

Tags: backbone javascript