实现:
class MyEventBus{
constructor() {
this.eventQueue = {}
}
on(eventName, callback) {
if (!this.eventQueue[eventName]) {
this.eventQueue[eventName] = []
}
this.eventQueue[eventName].push(callback)
}
once(eventName, callback) {
let wrap = (...argus) => {
callback.apply(this, argus)
this.off(eventName, wrap)
}
this.on(eventName,wrap)
}
emit(eventName, ...argus) {
if(this.eventQueue[eventName]) {
for(let callback of this.eventQueue[eventName]){
callback(...argus);
}
}
}
off(eventName, callback) {
let cbList = this.eventQueue[eventName];
if(cbList) {
if(callback) {
cbList.forEach((item, index) => {
if (item == callback) cbList.splice(index, 1)
})
} else {
cbList.length = 0;
}
}
}
}
测试:
const EventBus = new MyEventBus()
EventBus.once('first-event', function(msg) {
alert(`订阅的消息是:${msg}`);
});
EventBus.emit('first-event', "123")
EventBus.emit('first-event', "456")
EventBus.off('first-event')