/*
 * @Purpose: vue项目中的全局调用事件
 * @FilePath: eventBus.ts
 * @Author: sujunling
 * @Date: 2022-11-15 16:18:08
 * @Original: original
 * @Descripttion:
 */

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

type ParamsKey = string | number | symbol;

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

class EventBus implements eventBusClass {
  list: List;

  constructor() {
    this.list = {};
  }

  emit(name: string, ...args: Array<any>) {
    let eventName: Array<Function> = this.list[name];
    try {
      eventName.forEach((fn) => {
        fn.apply(this, args);
      });
    } catch (error) {
      console.log(error);
    }
  }

  on(name: string, callback: Function) {
    let fn: Array<Function> = this.list[name] || [];
    fn.push(callback);
    this.list[name] = fn;
  }
}
export default new EventBus();
