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 attr = `delegate-${type}-key`
|
|
|
|
let key
|
|
|
|
let element = target
|
|
|
|
while (element) {
|
|
|
|
if ((key = element.getAttribute(attr))) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
element = element.parentElement
|
|
|
|
}
|
|
|
|
if (key && callbacks[type] && callbacks[type][key]) {
|
|
|
|
callbacks[type][key](e)
|
|
|
|
}
|
|
|
|
stop('delegate onEvent')
|
|
|
|
}
|
|
|
|
|
2018-02-11 17:37:13 +00:00
|
|
|
export function registerDelegate (type, key, callback) {
|
2018-02-10 19:30:13 +00:00
|
|
|
mark('delegate registerDelegate')
|
|
|
|
callbacks[type] = callbacks[type] || {}
|
|
|
|
callbacks[type][key] = callback
|
|
|
|
stop('delegate registerDelegate')
|
|
|
|
}
|
|
|
|
|
2018-02-11 17:37:13 +00:00
|
|
|
export function unregisterDelegate (type, key) {
|
2018-02-10 19:30:13 +00:00
|
|
|
mark('delegate unregisterDelegate')
|
|
|
|
callbacks[type] = callbacks[type] || {}
|
|
|
|
delete callbacks[type][key]
|
|
|
|
stop('delegate unregisterDelegate')
|
|
|
|
}
|
|
|
|
|
|
|
|
if (process.browser) {
|
|
|
|
document.addEventListener('click', onEvent)
|
|
|
|
document.addEventListener('keydown', onEvent)
|
2018-02-11 17:37:13 +00:00
|
|
|
}
|