实际上EventBus就是一个发布订阅模式,简单实现如下
class EventBus {
constructor() {
this.onList = []
}
on(name, fn) { //订阅事件
this.onList.push({
name,
fn,
isOnce: false
})
}
emit(name, targetVal) { //发布事件
this.onList.forEach((obj, index) => {
if (obj.name === name) {
obj.fn(targetVal)
if (obj.isOnce) this.onList.splice(index, 1)
}
})
}
once(name, fn) {
this.onList.push({
name,
fn,
isOnce: true
})
}
off(name) {
const index = this.onList.findIndex(val => val.name === name)
if (index > -1) this.onList.splice(index, 1)
}
}
module.exports = EventBus
使用
const EventBus = require('./EventBus.js')
const bus = new EventBus()
bus.on('log', value => {
console.log('触发' + value)
})
bus.once('onceLog', value => {
console.log('触发一次' + value)
})
bus.off('log')
bus.emit('log', 'emit的值')
bus.emit('log', 'emit的值')
bus.emit('onceLog', 'onceLog的值')
bus.emit('onceLog', 'onceLog的值')