Skip to content

Instantly share code, notes, and snippets.

@searls
Last active May 29, 2018 12:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/020cb6be12fcf7463a1b7d0a66af3ef8 to your computer and use it in GitHub Desktop.
Save searls/020cb6be12fcf7463a1b7d0a66af3ef8 to your computer and use it in GitHub Desktop.
A handy way to forward global-ish events to functional components (Preact)
/* 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