Keyboard Shortcuts
import { registerKeyboardShortcut } from 'cx/ui';CxJS contains built-in functionality that listens for keyboard shortcuts.
ControllerWidget
class PageController extends Controller {
onInit() {
this.unregisterSimple = registerKeyboardShortcut(KeyCode.enter, (e) => {
this.store.toggle("simple");
});
this.unregisterComplex = registerKeyboardShortcut(
{ keyCode: KeyCode.a, shiftKey: true },
(e) => {
this.store.toggle("complex");
}
);
}
onDestroy() {
this.unregisterSimple();
this.unregisterComplex();
}
}registerKeyboardShortcut method accepts two arguments: key (one specific key or a combination
of keys, e.g. Shift + A), and a callback that is called when matching keyboard shortcut is pressed.
When key argument denotes a specific key, it's passed as a number (from the KeyCode enum).
Otherwise, it's passed as an object containing these fields:
keyCode(required): a number from theKeyCodeenum, e.g.KeyCode.enterctrlKey(optional): a boolean value representing whether the control key is part of the shortcutshiftKey(optional): a boolean value representing whether the shift key is part of the shortcutaltKey(optional): a boolean value representing whether the alt key is part of the shortcut
One thing worth mentioning is that you should unregister keyboard listeners when they're no longer needed, to prevent memory leaks and unexpected behavior. Good places to do that include controller's
onDestroymethod and component'scomponentWillUnmountmethod.