观察者与订阅者

观察者模式(Observer)又被称为发布-订阅者模式或消息机制,定义了一种依赖关系,解决了主体对象与观察者之间功能的耦合。

在之前的文章自定义事件二中有简单的介绍,本文中将会对其重新封装,详细如下:

class Observer {
  constructor () {
    this._topics = {}
  }

  observers (name, fn) {
    name.replace(/\S+/g, name => {
      fn.call(this, this._topics[name] || [], name)
    })
  }

  emit (name, ...args) {
    return this.observers(name, observers => {
      for (let i = 0, l = observers.length; i < l; i++) {
        const observer = observers[i];
        const fn = observer[0]
        let count = observer[1]
        count === 0 && observers.splice(i--, 1) && l--
        if (count !== 0) {
          typeof fn === 'function' && fn.apply(this, args)
          observer[1]--
        }
      }
      this._topics[name] = observers
    })
  }

  on (name, fn, count) {
    return this.observers(name, observers => {
      if (!(name in this._topics)) {
        this._topics[name] = observers
      }
      observers.push([fn, count])
    })
  }

  one (name, fn) {
    this.on(name, fn, 1)
  }

  off (name) {
    return this.observers(name, () => {
      delete this._topics[name]
    })
  }
}

测试结果

const instance = new Observer()
instance.on('add', (a, b) => console.log(a + b), 2)
instance.on('add', (a, b) => console.log(a * b), 1)
instance.emit('add', 1, 2)
instance.emit('add', 1, 8)
instance.emit('add', 1, 6)

//输出
// 3
// 2
// 9
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注