设计模式:发布订阅模式

调度中心

class Center {
      constructor () {
        this.message = {}
      }

      //订阅
      on (type, fn) {
        if (this.message[type] === undefined) {
          this.message[type] = []
        }
        this.message[type].push(fn)
      }

      //取消订阅
      off (type, fn) {
        if (this.message[type] === undefined) throw Error('未订阅此事件')
        if (!fn) return delete this.message[type] 
        this.message[type] = this.message[type].filter(item => item !== fn)
      }

      //触发
      emit (type) {
        if (this.message[type] === undefined) return
        this.message[type].forEach(item => {
          item()
        })
      }
    }

相关方法

订阅

  • 订阅者可以在调度中心订阅一系列事件
on (type, fn) {
        if (this.message[type] === undefined) {
          this.message[type] = []
        }
        this.message[type].push(fn)
      }

取消订阅

  • 订阅者可以取消事件的全部处理函数
  • 订阅者也可以取消事件的某个处理函数
  • 当取消未被订阅的事件时,就会抛出错误
off (type, fn) {
        if (this.message[type] === undefined) throw Error('未订阅此事件')
        if (!fn) return delete this.message[type] 
        this.message[type] = this.message[type].filter(item => item !== fn)
      }

触发

emit (type) {
        if (this.message[type] === undefined) return
        this.message[type].forEach(item => {
          item()
        })
      }

示例

  • 实例化调度中心
    const center = new Center()
  • 订阅a, b, c 三个事件
	center.on('a', handler1)
    center.on('a', handler2)
    center.on('b', handler3)
    center.on('b', handler4)
    center.on('c', handler5)
    center.on('c', handler6)
    function handler1 () { console.log('handler1') }
    function handler2 () { console.log('handler2') }
    function handler3 () { console.log('handler3') }
    function handler4 () { console.log('handler4') }
    function handler5 () { console.log('handler5') }
    function handler6 () { console.log('handler6') }
  • 取消订阅事件a的所有处理函数
center.off('a')
  • 取消事件a 的处理函数handler2
center.off('a', handler2)
  • 触发事件 a
center.emit('a')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值