I’m having trouble adding an event listener. I’m basically encapsulating all keyboard-related functions into a JavaScript class like so:
function Keyboard()
{
this.key = new Array();
for(x=0;x<255;x++)
{
this.key[x] = false;
}
function keyDown(evt)
{
this.key[evt.keyCode] = true;
console.log("Keydown bioch");
}
function keyUp(evt)
{
this.key[evt.keyCode] = false;
}
window.addEventListener('keydown', this.keyDown, true);
window.addEventListener('keyup', this.keyUp, true);
}
Except that it doesn’t work – at all. When I remove the Keyboard function and make everything global (key[], keyDown, keyUp, and addEventListener calls), everything works.
What am I doing wrong?
You’re using the
thiskeyword where it’s not appropriate. Also, your objects have nokeyDown/keyUpproperties.You will need to dereference the array, as
thisin a listener would point to the event-receiving (dom) element – which has nokeyproperty. And to reference your local functions, just use their names: