刘明野

js ts 简单的实现事件订阅发布

export type EventBusListener<P = any> = (payload?: P) => void

class EventBus {
  private list

  constructor() {
    this.list = new Map<string, EventBusListener[]>()
  }

  // 订阅
  $on(key: string, listener: EventBusListener) {
    if (!this.list.has(key)) {
      this.list.set(key, [])
    }
    this.list.get(key)?.push(listener)
    const _off = () => this.$off(key, listener)
    return _off
  }

  // 发布
  $emit(key: string, data: any) {
    this.list.get(key)?.forEach((fn) => fn(data))
  }

  // 取消订阅
  $off(key: string, listener?: EventBusListener) {
    if (listener === undefined) {
      this.list.delete(key)
    } else {
      const listeners = this.list.get(key)
      if (!listeners) {
        return
      }
      const index = listeners.indexOf(listener)
      if (index > -1) {
        listeners.splice(index, 1)
      }
      if (!listeners.length) {
        this.list.delete(key)
      }
    }
  }
}
export default new EventBus()
本文为作者刘明野发布,未经允许禁止转载!
1813
0
4
发表留言

友情链接