Skip to content

Instantly share code, notes, and snippets.

@romaricpascal
Created April 1, 2022 14:15
Show Gist options
  • Save romaricpascal/3e3775963984d28b2fc13083092eaf46 to your computer and use it in GitHub Desktop.
Save romaricpascal/3e3775963984d28b2fc13083092eaf46 to your computer and use it in GitHub Desktop.
Map keyboard events to `on{event.code}` methods
/**
* 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