Javascript MVC with Backbone.js

27 January 2012COMMENTS

As single page Javascript powered web apps have become increasingly commonplace recently, so too has the need to better structure Javascript code. A growing number of frameworks using the MVC design pattern have emerged including Sproutcore, Cappuccino, Sammy.js, Batman.js, Ember.js, Spine.js and the popular Backbone.js.

What is MVC?

The Model View Controller design pattern has been with us for some time and comes in different flavours as it attempts to solve different problems. Models are used to represent and manage data internally in an application and Views represent the data to the user. Controllers respond to user input and act on the models, they can be used to ensure that updates to Models are represented in multiple views of the data. MVC is very popular in web applications where Views are made up of HTML, Controllers handle GET and POST requests and call Model objects which usually represent database tables.

MVC diagram

The MVC Design Pattern

MVC in Backbone.js

Javascript MVC frameworks help to give structure to web applications which make heavy use of front-end Javascript. They implement MVC in various ways - in Backbone.js there are no Controllers, for example (Backbone.js used to include Controllers but they have been renamed as Routers to better reflect their function within Backbone.js).

Models in Backbone.js

Models contain the data of our Javascript application, Models are created and instantiated as follows:

MyModel = Backbone.Model.extend({
defaults: {
name: 'Jason'
},
initialize: function(){
alert("Hello World");
}
});

var myModel = new MyModel;

Default values can be added to the defaults property. The initialize function is called on creation of an instance, here events can be bound to attributes to respond to changes in their values. Backbone.js also supports Collections which are ordered sets of Models.

Views in Backbone.js

Views are used to represent the state of the data in our Models. They listen and respond to user events.

MyView = Backbone.View.extend({
el: $('body'),
initialize: function(){
this.render();
},
render: function(){
$(this.el).append("<button id='btn'>Click Me!</button>");
},
events: {
'click button#btn': 'myMethod',
},
myMethod: function(){
alert('click!');
}
});

var myView = new MyView;

Every View has an 'el' property which references an element in the DOM (here it is referenced using jQuery). The initialize method is again called on instantiation of the View, here it calls the render method which updates the el property. The 'events' property allows us to add events to listen for.

Routers in Backbone.js

Routers in Backbone.js are used for routing URLs when using hash tags(#).

var AppRouter = Backbone.Router.extend({
routes: {
"/url/:id": "myMethod",
},
myMethod: function( actions ){
alert(id);
}
});

var app_router = new AppRouter;

Backbone.history.start();

<a href="#/posts/1">Activate Route</a>

'myMethod' will be called when following the link 'Activate Route'.

Backbone.js and similar frameworks are probably most appropriate for single page web applications and Ajax heavy sites. However, in helping to give structure to Javacript code it can be useful in a range of situations, and help us to avoid messy and difficult to maintain Javascript.

Share.

  • Facebook
  • Twitter
  • Delicious
  • StumbleUpon
  • MySpace
  • Digg
  • Netvibes
  • Tumblr
  • Bebo

Author.

Jason Carpenter
Jason Carpenter (Junior Developer)

Comments.

Why not be brave? Be the first to comment...

Add new comment.

You are commenting as a guest. Optional: Login below:
*Required fields

Labs are the views and thoughts of staff at Acknowledgement focused around making and doing digital things!

VISIT OUR MAIN SITE
  1. Privacy Policy
  2. T&Cs of business
  3. Website T&Cs
© Acknowledgement 2012. All rights reserved.