Skip to content

Instantly share code, notes, and snippets.

@alvinsj
Last active August 29, 2015 14:22
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 alvinsj/c6451a18817f76dac2e2 to your computer and use it in GitHub Desktop.
Save alvinsj/c6451a18817f76dac2e2 to your computer and use it in GitHub Desktop.
/** @jsx React.DOM */
// NOTE: This file is formatted for React.js + Browserify
// You might need to make some changes to use it without Browserify
var MousetrapMixin,
Mousetrap = require('br-mousetrap');
MousetrapMixin = {
/**
* Array for keeping track of shortcuts bindings
*/
mousetrapBindings: [],
/**
* Bind a function to a keyboard shortcut
*
* @param key
* @param callback
*/
bindShortcut: function (key, callback) {
Mousetrap.bind(key, callback);
this.mousetrapBindings.push(key);
},
/**
* Unbind a keyboard shortcut
*
* @param key
*/
unbindShortcut: function (key) {
var index = this.mousetrapBindings.indexOf(key);
if (index > -1) {
this.mousetrapBindings.splice(index, 1);
}
Mousetrap.unbind(binding);
},
/**
* Remove any Mousetrap bindings
*/
unbindAllShortcuts: function () {
if (this.mousetrapBindings.length < 1) {
return;
}
this.mousetrapBindings.forEach(function (binding) {
Mousetrap.unbind(binding);
});
},
/**
* Handle component unmount
*/
componentWillUnmount: function () {
// Remove any Mousetrap bindings before unmounting
this.unbindAllShortcuts();
}
};
module.exports = MousetrapMixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment