Jindra
Jindra

Reputation: 810

Event handler method of object

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

Answers (1)

univerio
univerio

Reputation: 20548

FOO.prototype.setListeners = function()
{
    var that = this;
    $("#but").click(function(){that.handler();});
}

Upvotes: 1

Related Questions