Javascript Class & Eventlistener
I have a basic javascript class with two properties. I want to log the value of one on a click event. Here is what I got: function Clicker(/*string*/var1, /*id*/var2) { this.na
Solution 1:
The value of this
depends on the context in which a function is called.
When the event listener fires, the function is called in the context of the element the event is associated with - not the object the function was copied from.
Use bind
to override the context (it generates a new function that calls the original function in whatever context you define).
element.addEventListener("click", this.clickevent.bind(this), false);
This is equivalent to:
element.addEventListener(
"click",
function (context) {
returnfunction () {
context.clickevent();
};
}(this),
false
);
Solution 2:
I think it might be a context issue, could the following work:
functionClicker(/*string*/var1, /*id*/var2) {
this.name = var1;
this.clickerid = var2;
var self = this;
this.clickevent = function() {
console.log("1: " + self.name);
console.log("2: " + this);
console.log("3: " + window.testClicker.name);
};
var element = document.getElementById(this.clickerid);
element.addEventListener("click", this.clickevent, false);
}
as you can see with the 2nd console.log
, this
refers to the checkbox, not the Cliker
object
Solution 3:
For the sake of completeness, there are three possible solutions:
- Using a closured variable as suggested in dm03514's answer.
- Using
bind
as suggested in Quentin's answer. - Using the event listener interface /
handleEvent
as suggested at Dealing with Scope in Object methods containing 'this' keyword called by Event Listeners .
Post a Comment for "Javascript Class & Eventlistener"