Friday, August 31, 2018

Javascript Class, var undefined in event listener




var Foo = (function(){

function Foo(){

this._s="string";
this.setButton();
};

Foo.prototype.setButton = function(){
document.getElementById('id').addEventListener('click', function(event) {
alert(this._s);
});
};


Foo.prototype.method = function(){
alert(this._s);
};

return Foo;

})();

var fo = new Foo();
fo.method();



I want to bind an event to a button, and execute a function whic use a 'private' var, when I click the button the function is correctly called but it can't see the var this._s (it writes 'undefined'). If I write fo.method() the string is correctly printed.
here is the jsfiddle: http://jsfiddle.net/wLm1v4La/1/


Answer



you have to set the context(this) of the function manually before passing it.



 Foo.prototype.setButton = function () {
var tmpFunc = function(evt){ alert(this._s); } //store the function
var boundFunction = tmpFunc.bind(this); //set the context manually

//pass the function now to eventlistener
document.getElementById('id').addEventListener('click',boundFunction);
};

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...