自定义事件总线
- 自定义事件总线属于一种观察者模式,其中包括三个角色:
- 发布者(Publisher):发出事件(Event);
- 订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler);
- 事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的;
class CWEventBus {
constructor() {
this.eventBus = {};
}
on(eventName, eventCallback, thisArg) {
let handlers = this.eventBus[eventName];
if (!handlers) {
handlers = [];
this.eventBus[eventName] = handlers;
}
handlers.push({
eventCallback,
thisArg,
});
}
off(eventName, eventCallback) {
let handles = this.eventBus[eventName];
if (!handles) {
return;
}
const newHandlers = [...handles];
for (let index = 0; index < newHandlers.length; index++) {
const handle = newHandlers[index];
if (handle.eventCallback === eventCallback) {
const handleIndex = handles.indexOf(handle);
handles.splice(handleIndex, 1);
}
}
}
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName];
if (!handlers) {
return;
}
handlers.forEach((item) => {
item.eventCallback.apply(item.thisArg, payload);
});
}
}
const eventbus = new CWEventBus();
function handleOn() {
console.log("handleOn 监听", this);
}
eventbus.on(
"aaa",
function () {
console.log("监听aaa", this);
},
{ name: "why" }
);
eventbus.on("aaa", handleOn, { name: "why2" });
eventbus.emit("aaa", 134);
eventbus.off("aaa", handleOn);
eventbus.emit("aaa", 123);