Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extends mousetrap.js to support passing a dictionary into bind method. Just include this js after you include mousetrap.
/**
* Overwrites default Mousetrap.bind method to optionally accept
* an object to bind multiple key events in a single call
*
* You can pass it in like:
*
* Mousetrap.bind({
* 'a': function() { console.log('a'); },
* 'b': function() { console.log('b'); }
* });
*
* And can optionally pass in 'keypress', 'keydown', or 'keyup'
* as a second argument
*/
Mousetrap = (function(Mousetrap) {
var self = Mousetrap,
_oldBind = self.bind,
args;
self.bind = function() {
args = arguments;
// normal call
if (typeof args[0] == 'string' || args[0] instanceof Array) {
return _oldBind(args[0], args[1], args[2]);
}
// object passed in
for (var key in args[0]) {
if (args[0].hasOwnProperty(key)) {
_oldBind(key, args[0][key], args[1]);
}
}
};
return self;
}) (Mousetrap);
Mousetrap=function(b){var c=b.bind,a;b.bind=function(){a=arguments;if("string"==typeof a[0]||a[0]instanceof Array)return c(a[0],a[1],a[2]);for(var b in a[0])a[0].hasOwnProperty(b)&&c(b,a[0][b],a[1])};return b}(Mousetrap);
@tombigel
Copy link

tombigel commented Oct 28, 2012

missing "return this" after binding dictionary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment