Sunday, July 21, 2013

Binding View with model

This article helps you to create a new View, bind it to a Model and display it in the html page.

Create a new model, say StudentModel

var Student = Backbone.Model.extend({
       defaults : {
              name : 'Ram',
              age : 22,
              score : 100
       }
}); 

Create a new View, say StudentView

var StudentView = Backbone.View.extend({
       // tagName: 'p',
       class: 'headClass',
       id: 'sViewId',
       initialize: function() {
              console.log('this is sort of a constructor');
              this.render();
       },
       render: function() {
              console.log('I am going to render');
              $(document.body).html(this.$el.html("I am a new student :-)"));
       }
});
In the above code, this.el will return the html code that this view has generated, in this case, it simple creates a div element.




If you say studentView.$el, then it returns jquery object of the el (which means you can run you jquery methods using this $el.
if you uncomment the tagName attribute in the StudentView and run the same thing again, you can see that the div is replaced with <p> tag. 

Hence the view is mapped to a html element, if you leave it without defining it, then it simply creates a empty div element - you can define whatever you want, <p>, <ul> <li> etc.,

Note that the render method is automatically called, actually we are calling it from the initialize method. initialize() is actually a constructor which will be called everytime you create an object of the view. This applies to all Backbone objects such as Model, View etc.,

Ok, lets bind the value from the model to the dom element <p>, hmmm, that's simple. 

var Student = Backbone.Model.extend({
       defaults : {
              name : 'Ram',
              age : 22,
              score : 100
       }
});

var StudentView = Backbone.View.extend({
       tagName: 'p',
       class: 'headClass',
       id: 'sViewId',
       initialize: function() {
              console.log('this is sort of a constructor');
              this.model = new Student();
              this.render();
       },
       render: function() {
              console.log('I am going to render');
              $(document.body).html(this.$el.html('I am  ' + this.model.get('name') + ' - my age is : ' + this.model.get('age')));
       }
});

The render method takes the template, normally picks the data and renders it.


Ok, lets see more in the next article.  






No comments:

Post a Comment