Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created June 3, 2021 07:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianrubisch/b40ca3dc086fca8ccdbce3485ee90de9 to your computer and use it in GitHub Desktop.
Save julianrubisch/b40ca3dc086fca8ccdbce3485ee90de9 to your computer and use it in GitHub Desktop.
// useHotkeys.js
import hotkeys from "hotkeys-js";
export const bindHotkeys = (controller) => {
hotkeys.filter = () => true;
for (const [hotkey, handler] of Object.entries(
controller.constructor.hotkeys
)) {
hotkeys(hotkey, (e) => controller[handler](e));
}
};
export const unbindHotkeys = (controller) => {
for (const hotkey in controller.constructor.hotkeys) {
hotkeys.unbind(hotkey);
}
};
// usage
import { bindHotkeys, unbindHotkeys } from "./useHotkeys";
export default class extends Controller {
static hotkeys = {
"cmd+b, ctrl+b, cmd+i, ctrl+i, cmd+u, ctrl+u": "handleFormatting",
};
connect() {
bindHotkeys(this)
}
disconnect() {
unbindHotkeys(this)
}
handleFormatting(e) {
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment