发布订阅模式

复制代码
// 发布订阅模式设计模式:跟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   ChoZ  阅读(13)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示