调度中心
class Center {
constructor () {
this.message = {}
}
on (type, fn) {
if (this.message[type] === undefined) {
this.message[type] = []
}
this.message[type].push(fn)
}
off (type, fn) {
if (this.message[type] === undefined) throw Error('未订阅此事件')
if (!fn) return delete this.message[type]
this.message[type] = this.message[type].filter(item => item !== fn)
}
emit (type) {
if (this.message[type] === undefined) return
this.message[type].forEach(item => {
item()
})
}
}
相关方法
订阅
on (type, fn) {
if (this.message[type] === undefined) {
this.message[type] = []
}
this.message[type].push(fn)
}
取消订阅
- 订阅者可以取消事件的全部处理函数
- 订阅者也可以取消事件的某个处理函数
- 当取消未被订阅的事件时,就会抛出错误
off (type, fn) {
if (this.message[type] === undefined) throw Error('未订阅此事件')
if (!fn) return delete this.message[type]
this.message[type] = this.message[type].filter(item => item !== fn)
}
触发
emit (type) {
if (this.message[type] === undefined) return
this.message[type].forEach(item => {
item()
})
}
示例
const center = new Center()
center.on('a', handler1)
center.on('a', handler2)
center.on('b', handler3)
center.on('b', handler4)
center.on('c', handler5)
center.on('c', handler6)
function handler1 () { console.log('handler1') }
function handler2 () { console.log('handler2') }
function handler3 () { console.log('handler3') }
function handler4 () { console.log('handler4') }
function handler5 () { console.log('handler5') }
function handler6 () { console.log('handler6') }
center.off('a')
center.off('a', handler2)
center.emit('a')