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 false
      }
      if (!fn) {
        fn && (fn.length = 0)
      } else {
        let fnIndex = fns.indexOf(fn)
        fns.splice(fnIndex, 1)
        return true
      }
    }

  }

  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‘, ‘袋鼠‘, ‘睡觉‘)
  console.log(emit.remove(‘person‘, function (name, age) {
    console.log(name, age)
  }))  // true

JS发布订阅者模式

上一篇:nginx部署SSL证书后,使用域名访问报错-net::ERR_SSL_PROTOCOL_ERROR


下一篇:IIS部署.net core 的程序后,如何查看控制台的日志?