使用 Class
class Event {
constructor() {
this.eventMap = {}
}
on(type, callback) {
this.eventMap[type] = this.eventMap[type] || []
this.eventMap[type].push(callback)
}
emit(type, ...args) {
if (!this.eventMap[type]) {
return
}
this.eventMap[type].forEach((item) => {
item(args)
})
}
off(type, callback) {
if (!this.eventMap[type]) {
return
}
const index = this.eventMap[type].indexOf(callback);
if (index < 0) {
return
}
this.eventMap[type].splice(index, 1);
}
once(type, callback) {
const fn = (params) => {
callback(params)
this.off(type, fn)
}
this.on(type, fn)
}
}
不使用 Class
const eventBus = {
map: {},
on: (name, fn) => {
eventBus.map[name] = eventBus.map[name] || []
eventBus.map[name].push(fn)
},
emit: (name, params) => {
if (!eventBus.map[name]) { return }
eventBus.map((item) => {
item(params)
})
},
off: (name, fn) => {
if (!eventBus.map[name]) { return }
const index = eventBus.map[name].indexOf(fn)
if (index < 0) { return }
eventBus.map[name].splice(index, 1)
}
}