Considering the following code:
controls = {
'w': 'up',
's': 'down',
'a': 'left',
'd': 'right'
};
keysPressed = [];
for (control in controls) {
direction = controls[control];
$(document).bind('keydown', control, function() {
keysPressed.push(direction);
});
}
Only the right direction gets bound, and it is bound to all four keys. This is obviously not intended, but what am I missing about JavaScript that prevents all the properties from being bound appropriately?
EDIT:
For clarification, I’m using jQuery.hotkeys to handle key names. And this is a snippet; you can assume all variables have been declared. Also, code is in a safety function wrapper.
SOLUTION:
I solved it with this modification:
controls = {
'w': 'up',
's': 'down',
'a': 'left',
'd': 'right'
};
keysPressed = [];
addToKeyPressArray = function(value) {
return function() {
keysPressed.push(value);
};
};
removeFromKeyPressArray = function(value) {
return function() {
keysPressed = keysPressed.filter(value);
};
};
for (control in controls) {
direction = controls[control];
$(document).bind('keydown', control, addToKeyPressArray(direction));
$(document).bind('keyup', control, removeFromKeyPressArray(direction));
}
That’s an odd JavaScript quirk.
Seems to me like it’s probably the basic “closure in for loop” issue that many people trip up on with JS.
An explanation and solution is easy to find via google, here’s one for example: http://www.mennovanslooten.nl/blog/post/62