Last active
December 27, 2021 05:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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