首页 > 其他分享 >用typescript实现一个event bus

用typescript实现一个event bus

时间:2022-10-11 22:55:51浏览次数:43  
标签:... typescript bus void args emitKey key event fn

一个简单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();

标签:...,typescript,bus,void,args,emitKey,key,event,fn
From: https://www.cnblogs.com/azoux/p/16782946.html

相关文章