Created
August 28, 2009 19:04
-
-
Save blatyo/177158 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var Hotkey = (function(){ | |
| var modifiers = ['ctrl', 'shift', 'alt']; | |
| var hotkeys = $H(); | |
| return { | |
| add: function(keyCombination, behavior, options){ | |
| var keys = keyCombination.split('+'); | |
| var mods = keys.union(modifiers); | |
| var key = keys.without.apply(keys, modifiers).reduce(); | |
| if(Object.isArray(key)) throw "Error: Hotkey can only contain one key that is not a modifier"; | |
| options = Object.extend({ | |
| element: document, | |
| bubble: false, | |
| retval: false | |
| }, options || {}); | |
| hotkeys.set(keyCombination, {options: options, handler: { | |
| keydown: function(event){ | |
| var triggered = Event.hasKeyEvent(Event['KEY_' + key.toUpperCase()]) | |
| || Event.hasKeyEvent(key.charCodeAt(0)); | |
| mods.each(function(mod){ | |
| triggered = triggered && event[mod + 'Key']; | |
| }); | |
| if(triggered) { | |
| behavior(event); | |
| if(!options.bubble) event.stopPropagation(); | |
| if(!options.retval) event.preventDefault(); | |
| } | |
| } | |
| }}); | |
| options.element.observeAll(hotkeys.get(keyCombination).handler); | |
| }, | |
| remove: function(keyCombination){ | |
| var hotkey = hotkeys.get(keyCombination) | |
| hotkey.options.element.stopObservingAll(hotkey.handler); | |
| } | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment