Javascript Key Handler

2.5k views Asked by At

I have a Javascript key handler function and I'm trying to use it in a game that I'm working out but it doesn't seem to be quite working and I'm not sure if its the editor or the code has errors. My code is as shown:

var myKey = {
    pressedKeys: [],
    LEFT: 37,
    UP: 38,
    RIGHT: 39,
    DOWN: 40,
    isPressed: function(zKey){
        return this.pressedKeys[zKey];
    },
    onkeyDown: function(event){
        this.pressedKeys[event.keyCode] = true;
    },
    onkeyUp: function(event){
        this.pressedKeys[event.keyCode] = false;   
    },
};

window.addEventListener("keydown", myKey.onkeyDown);
window.addEventListener("keyup", myKey.onkeyUp);

var checkInput = function(){
    if(myKey.pressedKeys[myKey.LEFT]){
        confirm("Pressed Left");
    }
}

var gameLoop = function(){
    checkInput();
    window.requestAnimationFrame(gameLoop);
}

The game loop animation frame is called the first time in a main function that's not shown here. I don't understand what could be going wrong. I tried hard coding numbers and still nothing but it could very well be my editor.

1

There are 1 answers

3
Guffa On

When you get a reference to a method and use that as an event handler, the function is no longer associated with the object. this inside the function is not a reference to the myKey object, but a reference to the window object (as that is the object where the event happens).

You can use the bind method to specify the context for the functions:

window.addEventListener("keydown", myKey.onkeyDown.bind(myKey));
window.addEventListener("keyup", myKey.onkeyUp.bind(myKey));

Note that the bind method is not supported in some older browsers, for example IE8 and older, so you would need a 'polyfill' if you need to support them. There is one in the documentation that I linked to above.

You can also use a function wrapper to call the methods:

window.addEventListener("keydown", function(e){ myKey.onkeyDown(e); });
window.addEventListener("keyup", function(e){ myKey.onkeyUp(e); });