发布者与订阅者之间没有关联,由调度中心来处理事件。
订阅者通过on
去订阅事件,发布者通过emit
去发布一个事件。
发布者不需要知道谁对这个事件做出回应,订阅者不需要知道事件什么时候触发。
可以多个订阅者订阅一个发布者的事件,发布者与订阅者是一对多的依赖关系。
class EventBus {
// 事件列表
list = {}
// 订阅事件
on(key, fn) {
if (!this.list[key]) {
// 一个发布事件类型的多个订阅事件
this.list[key] = []
}
this.list[key].push(fn)
}
// 解除订阅事件
off(key, fn) {
let fns = this.list[key]
if (!fns) return false
if (!fn) {
// 解除一个发布事件类型的所有订阅事件
fns && (fns.length = 0)
} else {
fns.forEach((cb, i) => {
if (cb === fn) {
fns.splice(i, 1)
}
})
}
}
// 发布事件
emit() {
let key = [].shift.call(arguments)
let fns = this.list[key]
if (!fns || fns.length === 0) {
// 没有订阅事件可以触发
return false
}
fns.forEach((fn) => {
fn.apply(this, arguments)
})
}
}
测试代码
const eventBus = new EventBus()
class Publisher {
constructor() {
this.lowPrice()
}
lowPrice() {
eventBus.emit('ready', 100)
}
}
class Subscriber {
constructor() {
this.getLowPrice()
}
getLowPrice() {
eventBus.on('ready', (data) => {
console.log('ready', data)
})
}
}
const subscriber = new Subscriber()
const publisher = new Publisher()