-1

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.

asked May 16, 2016 at 18:50
4
  • 2
    Maybe because this is in reference to the event and not the callee? What is your scope? Is this wrapped inside a block? Commented May 16, 2016 at 18:53
  • 1
    the context of your handleKeyPress function is being overridden by jQuery. To prevent that, you can explicitly bind the context yourself: $(document).keydown(this.handleKeyPress.bind(this)) Commented May 16, 2016 at 18:53
  • if you console.log(this) inside your switch statement I'll bet the this isn't in the context you expect. Why are you using this? Is this inside another object? If not update your definition to var turn = function(direction){...} and inside the case use turn('left'). Commented May 16, 2016 at 18:54
  • Thanks everyone! The problem is definitely this in an anonymous function. I'm trying too hard to force js to look like Java :/ Commented May 16, 2016 at 19:09

1 Answer 1

2

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
}
answered May 16, 2016 at 18:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.