发布订阅模式

// 发布订阅模式设计模式:跟eventListener思想一样
// 监听器
// function eventFn() {
//   console.log('e');
// }
// document.addEventListener('eee',eventFn)
// // 订阅中心
// const bus = new Event('eee')
// // 发布器
// document.dispatchEvent(bus)
// // 关闭监听
// document.removeEventListener('eee',eventFn)

// 实现订阅模式
interface I {
  on:(eventName:string, callback:Function) => void
  emit:(eventName:string, ...argument:any[]) => void
  once:(eventName:string, callback:Function) => void
  off:(eventName:string, callback:Function) => void,
  // Function[]是因为同个名字,有多个回调函数
  event:Map<string,Function[]>
}

class Ee implements I {
  // 变量定义一定要赋值
  event: Map<string, Function[]>
  constructor() {
    this.event = new Map()
  }
  on(eventName:string, callback:Function):void {
    // 判断当前事件名是否注册过
    if(this.event.get(eventName)) {
      // 如果有,则往该事件名对应的回调数组添加回调
      const callbackList = this.event.get(eventName)
      callbackList && callbackList.push(callback)
    } else {
      // 如果没有,注册该时间名,并添加对应的回调数组
      this.event.set(eventName,[callback])
    }
  }
  // argument是调用emit可以传参数
  emit(eventName:string, ...argument:any[]):void {
    // 取对应时间名的回调数组
    const callbackList = this.event.get(eventName)
    // 如果有
    if(callbackList) {
      // 遍历执行回调数组的事件
      callbackList.forEach(item => {
        // 并把回调参数提供给回调函数
        item(...argument)
      })
    }
  }
  off(eventName:string, callback:Function):void {
    // 取对应时间名的回调数组
    const callbackList = this.event.get(eventName)
    // 如果有
    if(callbackList) {
      // 则删除对应该回调函数
      callbackList.splice(callbackList.indexOf(callback),1)
    }
  }
  once(eventName:string, callback:Function):void {
    const cb = (...argument:any[]) => {
      // 执行一次
      callback(...argument)
      // 立刻删除
      this.off(eventName,callback)
    }
    // 先注册
    this.on(eventName,cb)
  }
}
const bus = new Ee()
function L(a:string) {
  console.log(a);
}
bus.on('LLL',L)
bus.emit('LLL','我来找LLL了') // 输出:我来找LLL了
bus.off('LLL',L)

 

posted on 2025-02-17 22:08  ChoZ  阅读(23)  评论(0)    收藏  举报

导航