Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created March 1, 2018 03:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nolanlawson/621081285dbbae5be97a2bdf7a6d7ce5 to your computer and use it in GitHub Desktop.
Save nolanlawson/621081285dbbae5be97a2bdf7a6d7ce5 to your computer and use it in GitHub Desktop.
SvelteJS click delegation example
<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>
// 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