Aug 14

Custom events and Key bindings = Match made in heaven?

Tech with tags: , 7 Comments »

On the back of my example enjoying the Observer pattern with custom events I have started to play with a pet project also involving custom events.

I love keyboard shortcuts. I hate the mouse. I wish that Web applications would offer more keyboard shortcuts a la Gmail, and wondered if there could be a generic way to tie keys to actions in an app. There are things such as accessKey, but we need more.

If you start to follow the pattern of creating named events for public integration points, then how about tieing in keys? I implemented this on the quote example, where you can now use up and down arrows, and N and P, to move through the list of names.

To use the system you declare the keys and tie them to events:

KeyBindings.add({
   eventname: 'action:move-up',
   // keys: KeyBindings.caseInsensitive('p'),
   keys: ['p', Key.ARROW_UP ],
   description: "Move up the stack"
});

KeyBindings.add({
   eventname: 'action:move-down',
   keys: ['n', Key.ARROW_DOWN ],
   description: "Move down the stack"
});

This code ties the keys to the actions, and thus fires those actions when pressed. Next, you need to capture those events to do the work when the key is fired:

document.observe('action:move-up', function(e) {
    Selection.moveUp();
});

document.observe('action:move-down', function(e) {
    Selection.moveDown();
});

With a standardized way of annotating events, interesting side effects appear. You can hit the ‘?’ key to bring down a heads up display sharing what keys do. You could imagine a Greasemonkey script, or browser plugin, that loads the keybindings.js code, and looks for the key binding definitions. The declaration could be done in HTML too, which could be found by the plugin and tied into the system. What do you think?