0

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?

2 Answers2

4

You're using the this keyword where it's not appropriate. Also, your objects have no keyDown/keyUp properties.

You will need to dereference the array, as this in a listener would point to the event-receiving (dom) element - which has no key property. And to reference your local functions, just use their names:

function Keyboard() {
    var arr = this.key = new Array();
    for(x=0;x<255;x++)
        arr[x] = false;

    function keyDown(evt) {
        arr[evt.keyCode] = true;
        console.log("Keydown bioch");
    }
    function keyUp(evt) {
        arr[evt.keyCode] = false;
    }

    window.addEventListener('keydown', keyDown, true);
    window.addEventListener('keyup', keyUp, true);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    @Sosukodo: Moreover, when you make global the content of KeyBoard class everything works because "this.keyDown" and "this.keyUp" are referencing to the "global Window object" (window). It contains the keyDown and keyUp functions like methods and you can refer them with the "this" keyword. – bitfox May 30 '12 at 23:54
  • ...but you should not, yes. I was quite sure he would call it with "new". – Bergi May 31 '12 at 00:00
  • Your code is correct. My comment is just a note to explain the behavior in the global scope. – bitfox May 31 '12 at 00:15
  • @Bergi Thank you for your answer. While I don't fully understand the intricacies of JavasScript, you've helped me fully understand why I loathe it. –  May 31 '12 at 22:52
0

The "this" references in the callback functions are referencing the window object, not the function scope as you might expect.

See this Answer.

JavaScript Callback Scope

Community
  • 1
  • 1
James
  • 710
  • 6
  • 19
  • I also appreciated your answer. However, I tend to accept those answers that give a complete code example + explanation. –  May 31 '12 at 22:54