Skip to content

Instantly share code, notes, and snippets.

@heyimalex
Created November 21, 2014 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyimalex/cbe1f5e162c01b463b56 to your computer and use it in GitHub Desktop.
Save heyimalex/cbe1f5e162c01b463b56 to your computer and use it in GitHub Desktop.
Mixin for components that bind to keyboard events using Mousetrap.
// Mixin for components that bind to keyboard events using Mousetrap.
// Use this.bind like you would Mousetrap.bind.
function nop(){}
module.exports = {
bind: function(keys, callback, action) {
this._mousetrapBindings.push([keys, action]);
Mousetrap.bind(keys, callback.bind(this), action);
},
unbindAll: function() {
var bindings = this._mousetrapBindings;
var len = bindings.length;
for (var i = 0; i < len; i++) {
var binding = bindings[i];
Mousetrap.bind(binding[0], nop, binding[1]);
}
this._mousetrapBindings = [];
},
componentWillMount: function() {
this._mousetrapBindings = [];
},
componentWillUnmount: function() {
this.unbindAll();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment