Here is a couple of helpers I wrote in jQuery for another project.
Maybe you can use some of it:
App = {
doStuff : function() {
// a custom action
},
attachKeyboard : function(map) {
jQuery(document).bind('keydown', {map: map, scope: this}, this.keyNav);
},
detachKeyboard : function(map) {
jQuery(document).unbind('keydown', this.keyNav);
},
keyNav : function(e) {
var key = e.keyCode || e.which;
var map = e.data.map;
var scope = e.data.scope;
var keymap = {
UP: 38,
DOWN: 40,
LEFT: 37,
RIGHT: 39,
RETURN: 13,
ESCAPE: 27,
BACKSPACE: 8
};
for( var i in map ) {
var k = i.toUpperCase();
if ( keymap[k] ) {
map[keymap[k]] = map[i];
}
}
if (typeof map[key] == 'function') {
map[key].apply(scope);
}
}
}
Use it like this:
App.attachKeyboard({
up: this.doStuff,
down: function() {
// some other action
},
16: function() {
// do stuff when charcode 16 is pressed
}
});
If you want to change actions, you can just unbind the keyboard and re-bind it:
App.detachKeyboard();
App.attachKeyboard({
up: function() {
// do stuff
}
});