其他分享
首页 > 其他分享> > JS发布订阅者模式

JS发布订阅者模式

作者:互联网

class MesNotify {
    constructor() {
      this.listeningList = []  // 监听列表
    }

    // 发布
    publicListen(key, fn) {
      (this.listeningList[key] || (this.listeningList[key] = [])).push(fn)
    }

    // 订阅
    trigger() {
      let triggerRef = Array.prototype.shift.call(arguments)
      if (!this.listeningList[triggerRef] || this.listeningList[triggerRef].length === 0) {
        return
      }
      let fns = this.listeningList[triggerRef]
      for (let i = 0, fn; fn = fns[i]; i++) {
        fn.apply(this, arguments)
      }
    }

    // 移除
    remove(key, fn) {
      let fns = this.listeningList[key]
      if (!fns) {
        return
      }
      if (!fn) {
        fn && (fn.length = 0)
      } else {
        let fnIndex = fns.indexOf(fn)
        this.splice(fnIndex, 1)
      }
    }

  }

  let emit = new MesNotify()
  emit.publicListen('person', function (name, age) {
    console.log(name, age)
  })

  emit.publicListen('animal', function (animal, hobby) {
    console.log(animal, hobby)
  })

  emit.trigger('person', '张三', 19)
  emit.trigger('animal', '袋鼠', '睡觉')

标签:订阅,fns,listeningList,JS,let,模式,key,emit,fn
来源: https://www.cnblogs.com/bitingBeast/p/15170277.html