naive-ui/packages/utils/scrollDelegate.js
07akioni ffad17ff1f fix(popover): some times it can't disappear normally when mouseleave
mouseleave event sometimes can't fire. So I detect mouseout outside the popover
and activator to make it disappear. Implementation has many tricks. Sigh, life
is so hard.
2019-07-18 00:32:01 +08:00

48 lines
1.3 KiB
JavaScript

class ScrollDelegate {
constructor () {
console.debug('[ScrollDelegate]: Ctor called')
this.handlers = new Map()
this.handlerCount = 0
this.handleScroll = this.handleScroll.bind(this)
}
handleScroll (e) {
const handlers = this.handlers.get(e.target)
if (handlers) {
for (const handler of handlers) {
handler(e)
}
}
}
unregisterHandler (el, handler) {
const handlers = this.handlers.get(el)
if (handlers) {
// console.debug(handler)
const handlerIndex = handlers.findIndex(h => handler === h)
// console.debug(handlerIndex)
if (~handlerIndex) {
handlers.splice(handlerIndex, 1)
--this.handlerCount
}
}
if (!this.handlerCount) {
console.debug('[ScrollDelegate]: remove handler from window')
window.removeEventListener('scroll', this.handleScroll, true)
this.handlers = new Map()
}
}
registerHandler (el, handler) {
if (!this.handlerCount) {
console.debug('[ScrollDelegate]: add handler to window')
window.addEventListener('scroll', this.handleScroll, true)
}
++this.handlerCount
if (this.handlers.get(el)) {
this.handlers.get(el).push(handler)
} else {
this.handlers.set(el, [handler])
}
}
}
export default new ScrollDelegate()