I am trying to use this.moveCursor with Backbone, but it says it is undefined when I console.log. The method is obviously defined so I am not sure what is wrong here.
At first I though it was because of this. and the switch statement not returning.
However, even when I console.log outside the switch statement, it the same.
Can anyone help?
setup: function(){
$(document).on('keydown', this.keyCode);
},
keyCode: function(e){
switch(e.keyCode) {
case 37: console.log(this.moveCursor(-1,0)); break; //undefined
case 38: return this.moveCursor(0,-1); break;
case 39: return this.moveCursor(1,0); break;
case 40: return this.moveCursor(0,1); break;
case 32: return play.selectBlock(); break;
case 13: return play.selectBlock(); break;
};
console.log(this.moveCursor()); //undefined
},
moveCursor: function(x, y){
var cursorSelected = play.get('cursorSelected'),
cursorX = play.get('cursorX'),
cursorY = play.get('cursorY');
console.log('moveCursor');
if(cursorSelected){
x += cursorX;
y += cursorY;
this.getBlock(x,y);
} else {
//
}
},
You have a context issue. The
thiskeyword will represent the caller of thekeyCode()function, no matter where thekeyCode()has been defined into.To know more about this try to
console.log( this ), it will show you what it reallythisin that moment of the execution.To solve this issue you can play with _.bindAll().
If the
keyCode()is a handler of aBackbone.View.eventsthe binding should be already done.Update
I see the
keyCode()is a handler of a normal jQuery event:The
_.bindAll()will work for it, also you can use a jQuery.proxy() like this: