首页 > Web开发 > 详细

JS发布订阅者模式

时间:2021-08-21 20:17:56      阅读:49      评论:0      收藏:0      [点我收藏+]
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发布订阅者模式

原文:https://www.cnblogs.com/bitingBeast/p/15170277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!