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?
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With