2019-07-17 01:35:11 +08:00
|
|
|
class ScrollDelegate {
|
2019-07-14 14:25:47 +08:00
|
|
|
constructor () {
|
2019-07-17 14:40:28 +08:00
|
|
|
console.debug('[ScrollDelegate]: Ctor called')
|
2019-07-14 14:25:47 +08:00
|
|
|
this.handlers = new Map()
|
|
|
|
this.handlerCount = 0
|
2019-07-17 01:35:11 +08:00
|
|
|
this.handleScroll = this.handleScroll.bind(this)
|
2019-07-14 14:25:47 +08:00
|
|
|
}
|
|
|
|
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) {
|
2019-07-17 14:40:28 +08:00
|
|
|
// console.debug(handler)
|
2019-07-14 14:25:47 +08:00
|
|
|
const handlerIndex = handlers.findIndex(h => handler === h)
|
2019-07-17 14:40:28 +08:00
|
|
|
// console.debug(handlerIndex)
|
2019-07-14 14:25:47 +08:00
|
|
|
if (~handlerIndex) {
|
|
|
|
handlers.splice(handlerIndex, 1)
|
2019-07-17 01:35:11 +08:00
|
|
|
--this.handlerCount
|
2019-07-14 14:25:47 +08:00
|
|
|
}
|
|
|
|
}
|
2019-07-17 01:35:11 +08:00
|
|
|
if (!this.handlerCount) {
|
2019-07-17 14:40:28 +08:00
|
|
|
console.debug('[ScrollDelegate]: remove handler from window')
|
2019-07-18 00:32:01 +08:00
|
|
|
window.removeEventListener('scroll', this.handleScroll, true)
|
2019-07-17 01:35:11 +08:00
|
|
|
this.handlers = new Map()
|
|
|
|
}
|
2019-07-14 14:25:47 +08:00
|
|
|
}
|
|
|
|
registerHandler (el, handler) {
|
|
|
|
if (!this.handlerCount) {
|
2019-07-17 14:40:28 +08:00
|
|
|
console.debug('[ScrollDelegate]: add handler to window')
|
2019-07-17 01:35:11 +08:00
|
|
|
window.addEventListener('scroll', this.handleScroll, true)
|
2019-07-14 14:25:47 +08:00
|
|
|
}
|
|
|
|
++this.handlerCount
|
|
|
|
if (this.handlers.get(el)) {
|
|
|
|
this.handlers.get(el).push(handler)
|
|
|
|
} else {
|
|
|
|
this.handlers.set(el, [handler])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-17 01:35:11 +08:00
|
|
|
export default new ScrollDelegate()
|