Created
April 1, 2022 14:15
-
-
Save romaricpascal/3e3775963984d28b2fc13083092eaf46 to your computer and use it in GitHub Desktop.
Map keyboard events to `on{event.code}` methods
This file contains hidden or 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
/** | |
* Creates an event handler for keyboard events | |
* that looks up the actual method to execute | |
* in a hash of methods using the event's `code`: | |
* | |
* ```js | |
* element.addEventListener(keydown, keyboardEventHandler({ | |
* onArrowUp(event) {}, | |
* onArrowDown(event) {}, | |
* ... | |
* })) | |
* ``` | |
* | |
* @param {Object} methods - The hash of methods | |
* @param {Function} options.getMethodName - Customize how the method name is derived from event (default `on{keyboardEvent.code}`) | |
* @param {Function} options.shouldPreventDefault - Customize if the handling the event should `preventDefault` (default `() => true`) | |
* @returns {Function} | |
*/ | |
function keyboardEventHandler( | |
methods, | |
{ | |
getMethodName = (keyboardEvent) => `on${keyboardEvent.code}`, | |
shouldPreventDefault = () => true, | |
} = {} | |
) { | |
return function (keyboardEvent) { | |
const methodName = getMethodName(keyboardEvent); | |
if (methods[methodName]) { | |
if (shouldPreventDefault(keyboardEvent)) { | |
keyboardEvent.preventDefault(); | |
} | |
methods[methodName](keyboardEvent); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment