Vue3 简单实现 EventBus

使用 TypeScript

interface BusClass {
  emit: (name: string) => void;
  on: (name: string, callback: Function) => void;
}

type ParamsKey = string | number | symbol;

type List = {
  [key: ParamsKey]: Array<Function>;
};

class Bus implements BusClass {
  list: List;
  constructor() {
    this.list = {};
  }
  emit(name: string, ...args: Array<Function>) {
    const eventName: Array<Function> = this.list[name];
    eventName.forEach((fn) => {
      fn.apply(this, args);
    });
  }
  on(name: string, callback: Function) {
    const fn: Array<Function> = this.list[name] || [];
    fn.push(callback);
    this.list[name] = fn;
  }
}

export default new Bus();

版权声明:本文为qq_45317278原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。