balping
balping

Reputation: 8008

JS class this with event listener

I have a class with a function which handles an event. But when the event listener calls the handler function the this keyword refers to the clicked element and not to the class. I would like to make the other variables / functions of the class visible from the handler function.

Have a look: http://jsfiddle.net/cy7uM/1/

(Use FireBug or some other debugger to see the console.log messages)

function Class(){
    this.hello = "Hello World";

    document.getElementById("c").addEventListener("click", this.clickHandler); //doesn't work when clicked
}

Class.prototype.clickHandler = function(){
    console.log(this);
    alert(this.hello);   
}

var myobj = new Class();

myobj.clickHandler(); //works

Upvotes: 0

Views: 193

Answers (1)

000
000

Reputation: 27247

try

function Class(){
    this.hello = "Hello World";

    document.getElementById("c").addEventListener("click", this.clickHandler.bind(this));
}

Upvotes: 2

Related Questions