发布订阅模式
js
class EventEmitter {
constructor() {
// 缓存列表
this.list = {}
}
// 订阅
on(event, cb) {
(this.list[event] || (this.list[event] = [])).push(cb)
}
// 发布
emit(event, ...args) {
this.list[event] && this.list[event].forEach(cb => {
cb(...args)
})
}
// 只订阅一次
once(event, onceCb) {
const cb = (...args) => {
onceCb(...args)
this.off(event, cb)
}
this.on(event, cb)
}
// 取消订阅
off(event, offCb) {
if (this.list[event]) {
let index = this.list[event].findIndex(cb => cb === offCb)
this.list[event].splice(index, 1)
if (this.list[event].length === 0) Reflect.deleteProperty(this.list, event);
}
}
}