Codebeerstartups

5. Explaining views in backbone js – Learning Backbone Js

Introduction

Featured

Backbone.js

5. Explaining views in backbone js – Learning Backbone Js

Posted by Mohit Jain on .

This entry is part 5 of 14 in the series for A Complete Guide for Learning Backbone Js


Agenda

In previous lessons, we saw how to define models and add validations. In this lesson, we will be checking out views in Backbone js. Views are basically how you display your data.

What we have till now

To make things simpler let’s remove validations and functions from the model. So we have this.

var Person = Backbone.Model.extend({
    defaults: {
        name: 'Guest User',
        age: 23,
        occupation: 'worker'
    }
});

So now we want to add a view for a person. For simplicity, let’s take about list items. So every person will be displayed in a li tag. To define that view lets create a person view, i.e.,

var PersonView = Backbone.View.extend({
    tagName: 'li'
});

Fire up the console and fire these commands

By default tagName is div. Here we specified it to use li. So if we see this output:

var personView = new PersonView();
personView.el //will tell you the view for the object. Right now its a blank "li" tag.
personView.$el // is jquery tied up view for this object.

Output on Chrome Console

Let’s head back to chrome developer tools and see what we have in this object.

Define a basic view

Adding HTML elements like class, id

You can also add other things like cs class name, element id, etc. using some other attributes like

var PersonView = Backbone.View.extend({
    tagName: 'li',
        className: 'person',
        id: 'person-id' // although this is not a good way but I think got the idea.
});

Rendering the view

So backbone offers constructor for the views, i.e., known as initializing, i.e., it will be automatically called when you initiate a view.

initialize: function(){
}

Backbone also provides a method render that will render out the output for the data of the model associated with that view. ie

render: function(){
}

So let’s add all these in out class, so we have something like this:

var Person = Backbone.Model.extend({
    defaults: {
        name: 'Guest User',
        age: 23,
        occupation: 'worker'
    }
});

var PersonView = Backbone.View.extend({
   tagName: 'li',

   initialize: function(){
     this.render();
   },

   render: function(){
     this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );
  }
});

// calls from console

// var person = new Person;
// var personView = new PersonView({ model: person });

So in the above code, we defined certain things.

  • initialize function that will call on PersonView initialization.
  • render method that adds the content in the view
  • initialize function is calling render method which will add content in view.

Fire up the console and fire these commands

Let’s head towards Chrome console and execute these commands to see what we have.

var person = new Person;
var personView = new PersonView({ model: person });
personView.el;

// lets create a new person and display that person in view..
var person = new Person({name: "Mohit Jain", age: 25, occupation: "Software Developer"})
var personView = new PersonView({ model: person });
personView.el;
$(document.body).html(personView.el);  // this is not ideal but good enough for demo.

Output on Chrome Console

Here is what we have on console:

views in backbone js - console output

Problem in the thought process.

I hope you got an idea. But the problem with this code is definition of render method, i.e.,

this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );

As our views get complexed like having images and other things. This will become messy. We are lucky that backbone js has templates for that. So let’s head to the new lesson templates in backbone js.


Source code

If you are facing any issues. Check out the source code files at github. I will be creating more and more directories in the same repo regarding each post. Still, if you have any doubts you can comment on the blog post itself, and I will try to reply back asap.

user

Mohit Jain

http://codebeerstartups.com

Rails Developer