自定义事件总线属于一种发布订阅模式,其中包括三个角色:
1. 发布者(Publisher):发出事件(Event)
2. 订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler)
3. 事件总线(EventBus):无论时发布者还是订阅者都是通过事件总线作为中台的
class EventBus {
emit(keyname, payload) {
if (this.handler && this.handler[keyname]) {
if (this.handler[keyname].length > 0) {
for (let i = 0; i < this.handler[keyname].length; i++) {
this.handler[keyname][i].call(null, payload)
}
}
} else {
console.warn(`还没有监听 ${keyname}`)
}
}
on(keyname, callback) {
if (!this.handler) {
this.handler = {}
}
if (!this.handler[keyname]) {
this.handler[keyname] = []
}
this.handler[keyname].push(callback)
}
off(keyname, fn) {
if (this.handler && this.handler[keyname]) {
if (this.handler[keyname].length > 0) {
const index = this.handler[keyname].findIndex(f => f === fn)
this.handler[keyname].splice(index, 1)
} else {
delete this.handler[keyname]
}
} else {
console.warn(`请先去注册 ${keyname}`)
}
}
once(keyname, callback) {
this.on(keyname, (params) => {
callback(params)
this.off(keyname, callback)
})
}
clear() {
if (this.handler) {
for (let key in this.handler) {
delete this.handler[key]
}
this.handler = null;
}
}
}
使用:
const eb = new EventBus()
const testFn = (params) => {
console.log(params)
}
eb.once('zdy', testFn)
exce.onclick = function () {
eb.emit('zdy', { title: '我触发了' })
}
cancel.onclick = function () {
eb.off('zdy', testFn)
}
clear.onclick = function() {
eb.clear()
}