发布者和订阅者完全解耦(通过消息队列进行通信)
适用场景:功能模块间进行通信,如Vue的事件总线。
ES6实现方式:
class eventManager {
constructor() {
this.eventList = {};
}
on(eventName, callback) {
if (this.eventList[eventName]) {
this.eventList[eventName].push(callback);
} else {
this.eventList[eventName] = [callback];
}
}
fire(eventName, data) {
if (
eventName in this.eventList &&
Array.isArray(this.eventList[eventName])
) {
this.eventList[eventName].forEach(callback => callback(data));
} else {
console.log(`${eventName} is not a resgisted event`);
}
}
off(eventName, callback) {
if (callback) {
if (
eventName in this.eventList &&
Array.isArray(this.eventList[eventName])
) {
let index = this.eventList[eventName].indexOf(callback);
index > -1 && this.eventList[eventName].splice(index, 1);
} else {
console.log(`${eventName} has not been listen`);
}
} else {
delete this.eventList[eventName]
}
}
}
let eventManager1 = new eventManager();
eventManager1.on("event", data => {
console.log(data);
});
eventManager1.fire("event", "haha");
eventManager1.off("event");