I'm still getting used to javascript's syntax. I'm trying to bind actions to keypresses, and there's some disconnect here i can't spot. Why does the switch case get called without issue, but the function it calls never executes?
this.init = function() {
$(document).keydown(this.handleKeyPress);
}
this.handleKeyPress = function(event) {
switch (event.which) {
case 37:
alert("key press"); //this executes
this.turn("left");
break;
case 38:
this.turn("up");
break;
case 39:
this.turn("right");
break;
case 40:
this.turn("down");
break;
}
}
this.turn = function(direction) {
alert(direction); //this does not
}
I think this is the only relevant code, but i'm happy to post more if helpful. Thanks for your help.
1 Answer 1
Most likely you are running into issues with what the meaning of "this" is. When you're inside of your anonymous function this refers to the anonymous function, not the outer function that it's nested in. You probably want to do something like this:
var myObj = this ;
myObj.init = function() {
$(document).keydown(myObj.handleKeyPress);
}
myObj.handleKeyPress = function(event) {
switch (event.which) {
case 37:
alert("key press"); //this executes
myObj.turn("left");
break;
case 38:
myObj.turn("up");
break;
case 39:
myObj.turn("right");
break;
case 40:
myObj.turn("down");
break;
}
}
myObj.turn = function(direction) {
alert(direction); //this does not
}
thisis in reference to the event and not the callee? What is your scope? Is this wrapped inside a block?handleKeyPressfunction is being overridden by jQuery. To prevent that, you can explicitly bind the context yourself:$(document).keydown(this.handleKeyPress.bind(this))console.log(this)inside your switch statement I'll bet thethisisn't in the context you expect. Why are you usingthis? Is this inside another object? If not update your definition tovar turn = function(direction){...}and inside the case useturn('left').thisin an anonymous function. I'm trying too hard to force js to look like Java :/