Last active
May 29, 2018 12:37
-
-
Save searls/020cb6be12fcf7463a1b7d0a66af3ef8 to your computer and use it in GitHub Desktop.
A handy way to forward global-ish events to functional components (Preact)
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
/* Was looking for a way to delegate global keyboard shortcuts in an app to small | |
* Preact components in a way that didn't require any of: | |
* • Binding and unbinding events on ancestor nodes by a component's render function | |
* • Calling a function from a render function to try to manage/track that event-binding state for me | |
* • Require me to adopt class-ey components for only this feature (binding and unbinding an out-of-scope event using lifecycle hooks) | |
*/ | |
const FORWARDING_RULES = [ | |
{node: document, event: 'keydown', test: e => e.keyCode === 13, delegate: '.handle-enter'} | |
] | |
const initEventForwarding = (rules) => { | |
rules.forEach(({node, event, test, delegate}) => { | |
node.addEventListener(event, (e) => { | |
document.querySelectorAll(delegate).forEach(recipient => { | |
if (!test || test(e)) { | |
recipient.dispatchEvent(new Event('event')) | |
} | |
}) | |
}) | |
}) | |
} | |
const exampleView = () => | |
h('div', {class: 'handle-enter', onEvent: (e) => { | |
alert('user hit enter') | |
}}, 'I am a view') | |
document.addEventListener('DOMContentLoaded', () => { | |
initEventForwarding(FORWARDING_RULES) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment