pinafore/routes/_utils/delegate.js

45 lines
1 KiB
JavaScript
Raw Normal View History

2018-02-10 19:30:13 +00:00
// Delegate certain events to the global document for perf purposes.
import { mark, stop } from './marks'
const callbacks = {}
if (process.browser && process.env.NODE_ENV !== 'production') {
window.delegateCallbacks = callbacks
}
2018-02-11 17:37:13 +00:00
function onEvent (e) {
2018-02-10 19:30:13 +00:00
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
}
mark('delegate onEvent')
2018-02-25 00:12:25 +00:00
let attr = `delegate-key`
2018-02-10 19:30:13 +00:00
let key
let element = target
while (element) {
if ((key = element.getAttribute(attr))) {
break
}
element = element.parentElement
}
2018-02-25 00:12:25 +00:00
if (key && callbacks[key]) {
callbacks[key](e)
2018-02-10 19:30:13 +00:00
}
stop('delegate onEvent')
}
2018-02-25 00:12:25 +00:00
export function registerClickDelegate (key, callback) {
callbacks[key] = callback
2018-02-10 19:30:13 +00:00
}
2018-02-25 00:12:25 +00:00
export function unregisterClickDelegate (key) {
delete callbacks[key]
2018-02-10 19:30:13 +00:00
}
if (process.browser) {
document.addEventListener('click', onEvent)
document.addEventListener('keydown', onEvent)
2018-02-11 17:37:13 +00:00
}