Chrinkus Chrinkus - 2 months ago 10
Javascript Question

addEventListener not working as expected

I'm converting a tutorial game into a stronger app pattern and ran into an issue refactoring my event listeners.

In the original code, I had the listeners set and callbacks defined in main function:

(function () {
"use strict";
GAME.init();
function main() {
GAME.stopMain = window.requestAnimationFrame(main);

GAME.draw();

GAME.update();
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
// stuff
}

function keyUpHandler(e) {
// stuff
}

main();
})();


When I swapped my listeners and callbacks out for a call to
GAME.inputs.init();
and created this method of
GAME.inputs
:

GAME.inputs: {
keyDownHandler: function() {
// stuff
},

keyUpHandler: function() {
// stuff
},

init: function() {
document.addEventListener("keydown", this.keyDownHandler, false);
document.addEventListener("keyup", this.keyUpHandler, false);
}
};


The event listeners stopped registering. I had this issue once before and just reverted to the old way but I'd like to understand WHY this doesn't work.

Answer

You need to call bind so the scope of this is not the document.

 document.addEventListener("keydown", this.keyDownHandler.bind(this), false);
 document.addEventListener("keyup", this.keyUpHandler.bind(this), false);

and depending on how it is initialized, it might actually be

document.addEventListener("keydown", this.inputs.keyDownHandler.bind(this), false);
 document.addEventListener("keyup", this.inputs.keyUpHandler.bind(this), false);
Comments