Skip to content

Instantly share code, notes, and snippets.

@RomkeVdMeulen
Last active December 27, 2021 05:59
Show Gist options
  • Save RomkeVdMeulen/e9468f694e5fe4d05430ee0cc51505f8 to your computer and use it in GitHub Desktop.
Save RomkeVdMeulen/e9468f694e5fe4d05430ee0cc51505f8 to your computer and use it in GitHub Desktop.
TypeScript decorator to apply to a method that should only be invoked in response to certain keypress events.
export const enum KeyCode {
ENTER = 13,
SPACE = 32
}
export function keyListener(keyCodes: KeyCode | KeyCode[]) {
if (!(keyCodes instanceof Array)) {
keyCodes = [keyCodes];
}
return (_target: any, _key: string, descriptor: PropertyDescriptor) => {
const decorated: Function = descriptor.value;
descriptor.value = function(event: KeyboardEvent) {
if (!event || !(event instanceof KeyboardEvent) || !(<number[]><any>keyCodes).includes(event.keyCode)) {
return;
}
event.preventDefault();
return decorated.apply(this, arguments);
}
}
}
import {keyListener, KeyCode} from "src/util/events";
class MyEventProcessor {
@keyListener(KeyCode.ENTER)
enterListener() {
console.log(this, arguments);
}
@keyListener([KeyCode.ENTER, KeyCode.SPACE])
multiListener() {
console.log(this, arguments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment