手写一个基于发布订阅模式的简单js事件

 
const eventBus = {
  //  创建一个订阅对象
  arrays: {},
 
  // 添加订阅
  on: function(type, fn) {
    this.arrays[type] = this.arrays[type] || []
    let flag = true
    for(let i = 0; i < this.arrays[type].length; i++) {
      if(this.arrays[type][i] === fn) {
        flag = false
        break;
      }
    }
    if(flag) this.arrays[type].push(fn)
  },
 
  // 发布订阅过的方法
  emit: function(type, ...args) {
    this.arrays[type] = this.arrays[type] || []
    if(this.arrays[type].length) {
      this.arrays[type].forEach(callback => {
        callback(...args)
      })
    }
  },
 
  // 取消订阅
  off: function(type, fn) {
    let args = Array.from(arguments)
    if(args.length === 0) {  // 取消所有订阅方法
      this.arrays = {}
    }else if(args.length === 1) {  // 取消某一事件的所有方法
      if(!this.arrays[type]) return
      this.arrays[type] = []
    }else if(args.length === 2) {
      if(!this.arrays[type]) return
      /**
       * 由于可能某type下有多个订阅
       * 删除数组自身元素时,自身长度和下表会发生变化
       * 所以采用逆向循环
       */
      for(let i = this.arrays[type].length - 1; i >= 0; i--) {
        if(this.arrays[type][i] === fn) {
          // fn是引用类型,比较的是引用地址
          this.arrays[type].splice(i, 1)
        }
      }
    }
  },
}
 
 
// 订阅
eventBus.on('click', function(data ,num1, num2, num3) {
  console.log(data, 'data----->>>')
  console.log(num1, 'num1----->>>')
  console.log(num2, 'num2----->>>')
  console.log(num3, 'num3----->>>')
})
 
eventBus.on('click', function(data,num1, num2, num3) {
  console.log(data,'data--->>>')
  console.log(num1, 'num1----->>>')
  console.log(num2, 'num2----->>>')
  console.log(num3, 'num3----->>>')
})
 
eventBus.on('test', function(data) {
  console.log(data,'试一试test---->>>')
})
 
// 取消订阅
eventBus.off('test')
 
// 发布
eventBus.emit('click', '触发click事件', 1, 2,3)
eventBus.emit('test', '触发test事件')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会说法语的猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值