HTML Dog
Skip to navigation

Backbone

Backbone.js (aka Backbone) is designed to add structure to client-side applications, to avoid a spaghetti-code mess.

In the words of Backbone.js:

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Models are where you keep your data, and in Backbone they are special JavaScript objects created from a Backbone’s built-in Model, optionally extended by you to add functionality. Making a Model looks something like this:


var jedi = new Backbone.Model({
    name: 'Yoda',
    age: 874
});

You can then connect this model up to a View that displays it to the user, via a template. The template is just HTML with special tags or other syntax used to indicate where the model’s data should go.

A view looks something like this, including adding it to the page and rendering it.


var jediView = new Backbone.View({
     model: jedi,
    tagName: 'div',
    jediTpl: _.template($('#jedi-template').html()),
     render: function () {
          this.$el.html(this.jediTpl(this.model.toJSON())));
          return this;
     }
});

jediView.$el.appendTo('body');

jediView.render();

A template, often kept in a script element with a type of “template”, contains the HTML that the view should use. For the above example, it might look something like this:


<script type="template" id="jedi-template">
     <h1><%- name %></h1>
     <h2><%- age %></h2>
</script>