JavaScript 发布-订阅设计模式实现 React EventBus(相当于vue的$Bus)非父子之间通信
提前声明:
我没有对传入的参数进行及时判断而规避错误,仅仅对核心方法进行了实现;解决了react的非父子间的通信;
参考文档:
https://github1s.com/browserify/events/blob/main/events.js
1.其中的一种实现的方式
首先先新建一个文件eventBus.tsx
class EventBus {
constructor() {
this.events = this.events || new Map(); // 储存事件/回调键值对
this.maxListeners = this.maxListeners || 10; // 设立监听上限
}// 触发名为type的事件
emit(type, ...args) {
let handler = null;
handler = this.events.get(type);
console.log('