Javascript keyboard event in object

I got my keyboard 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 putting all this into 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 the main loop I will put the action:

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

And now he is failing. An interesting part of the problem is that a warning is raised ("arrow!"), So the variable must also be modified ...

I would be grateful for any ideas.

+3
source share
3 answers

In the event handler, jQuery (and in DOM events) thisrefers to the element the event is subscribed to ( documentin the sample). Use closure if you want to refer to the source 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);
}
+2

keydown/up , . bind this. Prototype Framework :

function Tkeyboard() {
    this.rightPressed = false;

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

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

jQuery.

, , .

+4

this DOM ( document), . this javascript:

var a = {
    f: function () {}
};
var b = { f: a.f};
var f = a.f;
a.f(); // this === a
b.f(); // this === b
f(); // this === window

this :

function bind(func, that) {
    return function() {
        func.apply(that, arguments);
    }
}

//...
$(document).keydown(bind(this.onKeyDown, this));

:

function Tkeyboard() {
    var that = this;
// use 'that' from here on
+1

Source: https://habr.com/ru/post/1796544/


All Articles