Introduction to Backbone.js Views

[raw]In the last article about Models in Backbone, I wrote about how the Models carry on the task of encapsulation for our Application and provide a way to access and mutate the data. This concept can be further clarified with the help of Backbone View.

When you move more and more state manipulations in your javaScript code to enhance UI, animations or to add some additional features, you tend to lose the basic link of your programming logic : Spaghetti code – exactly my point! ;)

This is where Backbone views come to the rescue. Basically, a backbone view has 2 requirements :

  1. They need to be tied to a particular part of DOM
  2. They are assigned a Model (data) which is to be presented as an end result

The first responsibility of Backbone view is achieved by providing a “root” element (el) to any Backbone View upon its creation. This root element can be anything from your DOM – a div, a span or any user defined HTML attribute. (Although if you do not provide an el to Backbone View, it takes a <div> as its el by default)

In order to complete its second and most important task, a Model is tied to the Backbone View, however, not all Backbone Views can have Models attached to them. We define a Model and assign it to a View by simply providing the Model’s object as an attribute of the View object.

For example :

1
2
3
4
5
6
7
8
9
10
11
Model : StudentInfo
var studentInfo = Backbone.Model.extend({
default : {
firstName: '',
lastName : '',
contactNumber : ''
// default values of attributes of the model
},
url : '/beageek/portal/services/...'<wbr />,
//url for a model specifies the link to server, accessed while syncing the model data with server
});

Now, the view for representing the studentInfo model would look like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var studentView = Backbone.View.extend({
tagName: "div",
className: "student-class",
events: {
"click .displayDetails": "showDetails",
"click #ok":   "submitForm",
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
},
render: function() {
...
},
destroy : function(){
...
}
});

So, that’s how our basic Backbone View looks. Now let’s get into the details of the functions that make up our Backbone View. Firstly, the initialize method – It acts like a constructor of our java class (which gets called upon initialization of every new object of that class) So, the code responsible for setup phase like initialization of logical flags, etc. should go into this initialize method.

Next important method of our View is the render method. As the name suggests, the job of render is to “render” i.e. put things in proper order, assign values to objects, set up listeners and other such functions that need to be done not only the first time upon creation of object but subsequently during the lifecycle of your application. ( Confused? I’ll get to it with an example to decipher it in the later part..for now, just bear with faith :D )

The events in backbone view perform the important task of providing an interface between user actions and backend manipulation. As shown in our example, many different user actions lead to different events which can be identified based on the id of the target with which user interacted or its className. In our example, the click events on two DOM elements have been handled as an illustration – one element has id “ok” and other has class “displayDetails” (notice the ids preceding with # and class names with a dot). We will take backbone events ass a seperate topic as its intrinsics need to be discussed in further depth and it won’t be fair on the part of poor Backbone View – the hero of the moment J

As shown in studentView, there are also tagName and className attributes. The tagName attribute defines where in the HTML page that you are going to render, the view fits in. For example, if u provide tagName : div, all the rendering jobs of ur view (html template rendering, etc.) will be encapsulated inside this <div>. Another similar and important property of view is the ‘el’. In case you have a pre-rendered DOM werein you already have divs or li elements with ids defined, you just provide that id to the el property of the view and your view gets rendered there. Simple as that!

So, lets say I have objects of our studentInfo model representing information about two students like this:

1
2
3
4
5
6
7
8
9
10
var nameStudentInfo1 = new studentInfo({
firstName: 'Tony',
lastName : 'Stark',
contactNumber : '1-A3-i5ON3AN'
});
var nameStudentInfo2 = new studentInfo({
firstName: 'Thor',
lastName :'OdinSon',
contactNumber : '1-A3-G0D'
});

And, let’s say I have an HTML template rendered, that looks like this :

In order to render the objects of my studentView view (defined earlier) into the respective “li”s, all I need to do is assign respective el’s the ids of respective “li”s. Like this:

<div id=’namesDiv’>
</div>

1
2
3
4
var nameStudentView1 = new studentView({
el : '#nameStudent1'
model : nameStudentInfo1; // the model object that we created earlier
});
1
2
3
4
var nameStudentView2 = new studentView({ el
el : '#nameStudent2'
model : nameStudentInfo2; // the model object that we created earlier
});

and so on…

The className, as the name suggests refers to the ‘class’ to be applied to view’s DOM elements. Also we can assign model to a specific view object in the similar way as el is assigned. Not only this, there are a lot more options to customize the view as per your business intention of building that view.

For now, lets wrap up with this basic introduction to the elements that make up our backbone view.

More examples and usage alongwith the collective functioning of views with models, collections and event – handling, coming up next…

Stay tuned J Happy Backboning! ;)[/raw]

Vidhi Zala

Leave a Reply