发布者订阅模式

发布者订阅模式

/*
分析
有一个对象,一旦有变化则通知订阅者
实例:买东西
如果去买东西没货,给店员留下有货联系方式,当货物到了,商家按照订阅者要求进行通知
属性:消息队列 {
click:[fn1,fn2],
trigger:[fn1,fn2,fn3]
}
*/

  class Observer {
    constructor() {
      this.message = {};
    }
    /* 添加内容 */
    on(type, fn) {
        //判断是否存在
        if(!this.message[type])
        {
            this.message[type]=[];
        }
        this.message[type].push(fn);
    }
    /* 删除内容 取消订阅 */
    off(type, fn) {
      //如果fn不存在  
      if(!fn)
     {
      delete this.message[type];
      return
     }
     //如果类型不存在
     if(!this.message[type])
     return;
     //重新赋值
     this.message[type]=this.message[type].filter(item=>item!=fn);

    }
    /* 触发内容 */
    trigger(type) {
      if(this.message[type])
      {
          this.message[type].forEach(item => {
              item();
          });
      }
    }
  }
  const person1=new Observer();
  person1.on('三国演义',handlerA)
  person1.on('三国演义',handlerB)
  person1.on('水浒传',handlerC)
  person1.on('水浒传',handlerD)

  // person1.off('三国演义');
  person1.off('三国演义',handlerA)

  person1.trigger('三国演义');
  console.log(person1);
  function handlerA(){
      console.log('邮箱通知我--A');
  }
  function handlerB(){
      console.log('短信通知我--B');
  }
  function handlerC(){
      console.log('打电话告诉我--C');
  }
  function handlerD(){
      console.log('微信告诉我--D');
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,842评论 2 17
  • 详解 ps:什么是设计模式是设计思路,一定程度提高效率在基础的23中设计模式中进行使用和优化和改良。 1.发布-订...
    JX灬君阅读 575评论 0 1
  • 之前在看DMQ根据vue双向数据绑定原理模拟实现了mvvm,里面有提高发布者-订阅者模式,看了一些资料,今天自己简...
    一慢呀阅读 22,831评论 0 17
  • 相关命令 PSUBSCRIBE[https://redis.io/commands/psubscribe] PUB...
    颍水书生阅读 562评论 2 0
  • 一、前言 JS语言的执行环境是“单线程”,所以任务是一个一个进行执行,如果任务多就需要排队。如果任务多,浏览器加载...
    vinterx阅读 711评论 3 1