Chrinkus Chrinkus - 6 months ago 40
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";
function main() {
GAME.stopMain = window.requestAnimationFrame(main);



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

function keyDownHandler(e) {
// stuff

function keyUpHandler(e) {
// stuff


When I swapped my listeners and callbacks out for a call to
and created this method of

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.


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);