JavaScript学习笔记19-事件总线

on,emit,off监听

1. 自定义事件总线

  • 自定义事件总线属于一种观察者模式,其中包括三个角色

    • 发布者(Publisher):发出事件(Event)
    • 订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler)
    • 事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的
  • 可以选择一些第三方的库

    • Vue2默认是带有事件总线的功能
    • Vue3中推荐一些第三方库,比如mitt
  • 也可以实现自己的事件总线

    • 事件的监听方法on
    • 事件的发射方法emit
    • 事件的取消监听off
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class MyEventBus {
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) {
console.log(`取消监听 ${eventName}${eventCallback.name}`);
const handlers = this.eventBus[eventName];
if (!handlers) return;
const newHandlers = [...handlers];
for (let i = 0; i < newHandlers.length; i++) {
const handler = newHandlers[i];
if (handler.eventCallback === eventCallback) {
const index = handlers.indexOf(handler);
handlers.splice(index, 1);
}
}
}

emit(eventName, ...payload) {
const handlers = this.eventBus[eventName];
if (!handlers) return;
handlers.forEach((handler) => {
handler.eventCallback.apply(handler.thisArg, payload);
});
}
}

const myEvent = new MyEventBus();
myEvent.on(
"abc",
function () {
console.log("监听abc", this);
},
{ name: "why" }
);

function foo() {
console.log("监听cba", this);
}

myEvent.on("abc", foo, { name: "hello" });

myEvent.emit("abc", 123);

// 取消监听
myEvent.off("abc", foo);
myEvent.emit("abc",123);
本文结束  感谢您的阅读