Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a prototype function to an event listener in the initialization function?

I'm not sure exactly how to phrase my question, so let me present an example:

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

foo.prototype.bar = function (keycode) {
//code
}

I've tried using this.bar(), but that results in using the window as this. Is there a way to do this, or will I have to call another initialize method manually?

like image 416
Bloodyaugust Avatar asked Jul 06 '12 14:07

Bloodyaugust


People also ask

Can you add an event listener in an event listener?

The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Can you add two functions to an event listener?

We can invoke multiple functions on a single event listener without overwriting each other. To do this we simply call the addEventListener() method more than once with a different function. In the example above, we add another event listener for the same event on the same button.

How do you add an event listener to a variable?

To set up an event listener you just need to have a variable that references an element and then call the addEventListener function on that element. This function takes a minimum of two parameters. The first parameter is just a string which is the name of the event to listen to.


1 Answers

Bind this.bar to this before you pass 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/

like image 122
Esailija Avatar answered Sep 20 '22 17:09

Esailija