Sunday, July 21, 2013

Event handling backbone view


Include the following content in a html file.

<div id="nameDiv">
       <p> My name is : </p> <input type="text" id="txtName"> <br>
       <button id="btnChangeName"> Change Name</button>
</div>


Create a view and include the below content.
var StudentView = Backbone.View.extend({
       el: '#nameDiv',
       initialize: function() {
              console.log('this is sort of a constructor');
              this.render();
       },
       events : {
              'click #btnChangeName' : 'changeName'
       },
       changeName : function() {
              alert('Going to change name');
       },
      
       render: function() {
              console.log('I am going to render');
              this.model = new Student();
              $('#txtName').val(this.model.get('name'));
       }
});


The events attribute in the above code contains the code for handlign the button click events. 

Note that the view is mapped to the div called nameDiv and it will handle only events or operations related to this div alone. This covers all the elements inside this div (i.e., text box and button inside this div). 

Simple !!! No more cluttering the html code with event handling code.



No comments:

Post a Comment