I have a simple Backbone view which uses jQuery UI’s buttons.
For example I have a delete button, which should delete the model (and view). I managed to add the button to the view in the render method using the following:
var self = this;
$(this.el).find("#deleteButton").button({text : false});
$(this.el).find("#deleteButton").bind( "click", self.deleteView);
and then I have the corresponding method in the view:
deleteView: function(){
console.log(this.model);
}
The “deleteView” method gets called, but it will print “undefined” to the console, as “this” is referring to the button and not the view. Replacing “this” with “self” doesn’t work either. Also, passing the model or the view as an argument to the method doesn’t seem to work as the argument will be the click event.
What is the correct way to handle such callbacks with backbone?
You would want to use the
backbone.viewevents property instead. This is the suggested method rather than manually using jQuery to bind events to child elements during render. http://documentcloud.github.com/backbone/#View-delegateEventsWould be as simple as adding this to your view: