Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js initialize listeners vs events

I don't understand the difference between putting a "click" listener in an initialize function inside a view and putting it in the events object in the same view. They both listen for DOM events and trigger functions, right? What's the difference?

for example:

var ViewName = Backbone.View.extend({  
    initialize: function(){  
        this.$el.on("eventName", this.functionName, this)  
    },  
    functionName: function(){  
        //whatever  
    }  
});

versus:

var ViewName = Backbone.View.extend({  
    events: { "eventName": "fucntionName" }   
    },  
    functionName: function(){  
        //whatever  
    }  
});
like image 756
Eric Hannum Avatar asked Oct 02 '13 23:10

Eric Hannum


1 Answers

When you do:

var ViewName = Backbone.View.extend({  
   initialize: function(){  
      this.$el.on("eventName", this.functionName, this)  
   },  
   functionName: function(){  
    //whatever  
   }  
});

You have to manually unbind the event when the view is being removed. So, you would have to do something like:

var ViewName = Backbone.View.extend({  
   initialize: function(){  
      this.$el.on("eventName", this.functionName, this)  
   },  
   functionName: function(){  
    //whatever  
   },
   remove: function() {
      this.$el.off("eventName", this.functionName);
      Backbone.View.prototype.remove.apply(this, arguments);
   }  
});

If you use the events hash, Backbone takes care of undelegating events when the view is removed. This is all explained in this section of the Backbone.js annotated source.

like image 87
gbsice Avatar answered Oct 21 '22 13:10

gbsice