Vue EventBus代码实现

Vue 简易代码实现EventBus

EventBus代码

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

type PramsKey = string | number | symbol
type List = {
  [key in PramsKey]: Function[]
}

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

export default new Bus()

EventBus使用

const emitB = () => {
  flag = !flag
  Bus.emit("on-click", flag)
}

Bus.on("on-click", (flag: boolean) => {
  Flag.value = flag
})