Friday 31 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...