pinafore/routes/_utils/delegate.js

44 lines
1,008 B
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')
let key
let element = target
while (element) {
2018-03-01 03:16:11 +00:00
if ((key = element.getAttribute('delegate-key'))) {
2018-02-10 19:30:13 +00:00
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
}