Reputation: 810
I have a problem with variable scope. I am setting event listeners (onclick
), but the handler is method of an object and I need to refer to the object within the handler method.
Example:
var FOO = function () {
this.clicked = false
};
FOO.prototype.handler = function(e)
{
this.clicked = true;
}
FOO.prototype.setListeners = function()
{
$("#but").click(this.handler);
}
var oop = new FOO();
oop.setListeners();
Example works to the point this.clicked = true;
where because this
doesn't refer to the oop
.
How do I pass a reference of the object to the handler function?
Upvotes: 0
Views: 175
Reputation: 20548
FOO.prototype.setListeners = function()
{
var that = this;
$("#but").click(function(){that.handler();});
}
Upvotes: 1