用typescript实现一个event bus

一个简单event bus的实现

发布订阅者模式

type emitKey = number | string | symbol;
type func = (...args: any) => void;

interface BusInterface {
  emit: (key: emitKey, ...args: any) => void;
  on: (key: emitKey, fn: func) => void;
}

class Bus implements BusInterface {
  emit: (key: emitKey, ...args: any) => void = (key, ...args) => {
    const handlers: Array<func> = this.list[key] || [];
    handlers.forEach((fn: func) => fn(...args));
  };
  on: (key: emitKey, fn: func) => void = (key, fn) => {
    // register
    this.list[key] = this.list[key] || [];
    this.list[key].push(fn);
  };
  private list: { [key: emitKey]: Array<func> } = {};
}

export default new Bus();
posted @ 2022-10-11 22:49  azoux  阅读(59)  评论(0编辑  收藏  举报