How to add prototype function to event listener in initialization function?

I am not sure exactly how to formulate my question, so let me give you an example:

function foo() { window.addEventListener("keydown", function(event) { bar(event.keycode); } foo.prototype.bar = function (keycode) { //code } 

I tried using this.bar() , but this leads to using window like this . Is there a way to do this, or will I have to manually call another initialization method?

+6
source share
3 answers

Bind this.bar to this before passing it.

 function foo() { window.addEventListener("keydown", this.bar.bind(this), false); } foo.prototype.bar = function (event) { console.log(event.keyCode); } 

demo http://jsfiddle.net/2tee4/

+7
source

An alternative solution, if you do not have Function.prototype.bind available *, and you do not want to add additional functions to Function.prototype , would close the call to this.bar :

 function foo() { var self; self = this; window.addEventListener('keydown', function (e) { self.bar(e); }, false); } foo.prototype.bar = function (e) { console.log(e.keyCode); } 

*, although using addEventListener without attachEvent makes me think that Function.prototype.bind would be an acceptable choice


In addition, libraries such as jQuery can contain their own bind form, jQuery jQuery.proxy .

+5
source

If you intend to add a new listener for each foo created, another option is to make foo implement the EventListener interface and just pass this instead of the handler.

 function Foo() { window.addEventListener("keydown", this, false); } Foo.prototype.bar = "foobar"; Foo.prototype.handleEvent = function(e) { console.log(e.type); // "mousedown" (for example) console.log(this.bar); // "foobar" }; new Foo(); 

Note that this only works with addEventListener() .

DEMO: http://jsfiddle.net/k93Pr/

+4
source

Source: https://habr.com/ru/post/919856/


All Articles