Pinafore-Web-Client-Frontend/routes/_utils/delegate.js

44 lines
1008 B
JavaScript
Raw Normal View History

2018-02-10 20:30:13 +01: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 18:37:13 +01:00
function onEvent (e) {
2018-02-10 20:30:13 +01: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 04:16:11 +01:00
if ((key = element.getAttribute('delegate-key'))) {
2018-02-10 20:30:13 +01:00
break
}
element = element.parentElement
}
2018-02-25 01:12:25 +01:00
if (key && callbacks[key]) {
callbacks[key](e)
2018-02-10 20:30:13 +01:00
}
stop('delegate onEvent')
}
2018-02-25 01:12:25 +01:00
export function registerClickDelegate (key, callback) {
callbacks[key] = callback
2018-02-10 20:30:13 +01:00
}
2018-02-25 01:12:25 +01:00
export function unregisterClickDelegate (key) {
delete callbacks[key]
2018-02-10 20:30:13 +01:00
}
if (process.browser) {
document.addEventListener('click', onEvent)
document.addEventListener('keydown', onEvent)
2018-02-11 18:37:13 +01:00
}