Search code examples
javascripteventsobjectkeyboard

Javascript keyboard event in an object


I got my keyboard working in a simple way:

rightPressed = false;

onKeyDown = function(pressEvent) {
  if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
  if (pressEvent.keyCode == 39) rightPressed = false;
}

$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);

And it worked. Then i tried to put it all in a class:

function Tkeyboard(){
this.rightPressed = false;

this.onKeyDown = function(pressEvent) {
  if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
  if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}

$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}

In initialization I created an object:

keys = new Tkeyboard;

In main loop i put action:

if ( keys.rightPressed ) { rx+=1;}

And now it fails. The interesting part of the problem is that alert("boom!") is called, so variable should get modified too...

I would be grateful for any ideas.


Solution

  • In an event handler in jQuery (and in DOM events), this refers to the element the event is subscribed on (document in the sample). Use a closure if you want to refer to the original object.

    function Tkeyboard(){
        var self = this;
        this.rightPressed = false;
    
        this.onKeyDown = function(pressEvent) {
          if (pressEvent.keyCode == 39) { self.rightPressed = true; alert("boom!"); }
        }
        this.onKeyUp = function(pressEvent) {
          if (pressEvent.keyCode == 39) { self.rightPressed = false; }
        }
    
        $(document).keydown(this.onKeyDown);
        $(document).keyup(this.onKeyUp);
    }