微信小程序使用事件总线,在页面、组件之间通信

用typescript 写了一个单例事件总线类,可在微信小程序不同页面、组件中通信,类里只提供事件注册 on、事件取消 off、事件发送 emit,三个公共方法

/**
 * 自定义事件 总线
 */
export default class EventBus {
  public static updateData: string = 'updateData'; //更新数据
  private static _ins: EventBus;
  public static get ins(): EventBus {
    if (EventBus._ins == null) {
      EventBus._ins = new EventBus();
    }
    return EventBus._ins;
  }
  private _events: Map<string, Function[]>;
  constructor() {
    this._events = new Map()
  }
  //注册一个事件
  public on(eventType: string, cb: Function): void {
    if (this._events.has(eventType)) this._events.get(eventType)?.push(cb);
    else this._events.set(eventType, [cb]);
  }
  //移除事件
  public off(eventType: string, cb: Function): void {
    if (!this._events.has(eventType)) return;
    const cbs = this._events.get(eventType);
    if (!cbs) return;
    for (let i = cbs.length - 1; i >= 0; i--) {
      if (cbs[i] === cb) {
        cbs.splice(i, 1);
        return;
      }
    }
  }
  //发送事件
  public emit(eventType: string, data: any = null): void {
    if (!this._events.has(eventType)) return;
    const cbs = this._events.get(eventType);
    if (!cbs) return;
    for (let i = 0; i < cbs.length; i++) {
      cbs[i](data);
    }
  }
}
使用方法

1.将上面的类代码保存到一个.ts文件中
2.在需要使用的页面或组件中引入,例如:

import EventBus from '../../utils/eventbus';

3.page中使用
在onLoad 注册事件,在onUnload 移除事件

  onLoad() {
    EventBus.ins.on(EventBus.updateData, this.update);
  },
  update(e: any) {
    console.log('***********:index 接收数据::', e)
  },
  onUnload() {
    EventBus.ins.off(EventBus.updateData, this.receive);
  }

4.在component中使用
在created中 注册事件,在detached 中移除事件

methods: {
    receive(e: any) {
      console.log('**********:::comp2 收到数据:', e)
    }
  },
  lifetimes: {
    created() {
      EventBus.ins.on(EventBus.updateData, this.receive);
    },
    detached() {
      EventBus.ins.off(EventBus.updateData, this.receive);
      console.log('************detached');
    }
  }

5.发送事件

  EventBus.ins.emit(EventBus.updateData, { a: 10, b: 20 }); 

6.效果,在不同页面、组件中收到事件及传过来的参数

***********:index 接收数据:: {a: 10, b: 20}
**********:::comp2 收到数据: {a: 10, b: 20}
********logis 收到数据: {a: 10, b: 20}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容