Created
March 1, 2018 03:11
-
-
Save nolanlawson/621081285dbbae5be97a2bdf7a6d7ce5 to your computer and use it in GitHub Desktop.
SvelteJS click delegation example
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
<button delegate-key="foo">Click me</button> | |
<script> | |
import { registerClickDelegate, unregisterClickDelegate } from './delegate' | |
export default { | |
oncreate() { | |
registerClickDelegate('foo', () => { | |
console.log('clicked!') | |
}) | |
}, | |
ondestroy() { | |
this.onClick = this.onClick.bind(this) | |
unregisterClickDelegate('foo') | |
}, | |
} | |
</script> |
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
// Delegate certain events to the global document for perf purposes. | |
const callbacks = {} | |
if (process.browser && process.env.NODE_ENV !== 'production') { | |
window.delegateCallbacks = callbacks | |
} | |
function onEvent (e) { | |
let { type, keyCode, target } = e | |
if (!(type === 'click' || (type === 'keydown' && keyCode === 13))) { | |
// we're not interested in any non-click or non-Enter events | |
return | |
} | |
let attr = `delegate-key` | |
let key | |
let element = target | |
while (element) { | |
if ((key = element.getAttribute(attr))) { | |
break | |
} | |
element = element.parentElement | |
} | |
if (key && callbacks[key]) { | |
callbacks[key](e) | |
} | |
} | |
export function registerClickDelegate (key, callback) { | |
callbacks[key] = callback | |
} | |
export function unregisterClickDelegate (key) { | |
delete callbacks[key] | |
} | |
if (process.browser) { | |
document.addEventListener('click', onEvent) | |
document.addEventListener('keydown', onEvent) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment