zoukankan      html  css  js  c++  java
  • js 实现发布订阅模式

         /* Pubsub */
          function Pubsub(){
            //存放事件和对应的处理方法
            this.handles = {};
          }
          
          Pubsub.prototype = {
            //传入事件类型type和事件处理handle
            on: function (type, handle) {
              if(!this.handles[type]){
                this.handles[type] = [];
              }
              this.handles[type].push(handle);
            },
            emit: function () {
              //通过传入参数获取事件类型
              //将arguments转为真数组
              var type = Array.prototype.shift.call(arguments);
              if(!this.handles[type]){
                return false;
              }
              for (var i = 0; i < this.handles[type].length; i++) {
                var handle = this.handles[type][i];
                //执行事件
                handle.apply(this, arguments);
              }
            },
            off: function (type, handle) {
              handles = this.handles[type];
              if(handles){
                if(!handle){
                  handles.length = 0;//清空数组
                }else{
                for (var i = 0; i < handles.length; i++) {
                  var _handle = handles[i];
                  if(_handle === handle){
                    //从数组中删除
                    handles.splice(i,1);
                  }
                }
              }
            }  
          }
    
    
          let p1 = new Pubsub();
          p1.on('detail', (name)=> {console.log(name)});
          p1.emit('detail', 'observer')
          let p2 = new Pubsub();
          p2.on('detail', (name)=> {console.log(name)});
          p2.emit('detail', 'observer2')
          p2.off('detail');
          p2.emit('detail', 'observer3');

    转自 https://segmentfault.com/a/1190000012430769

  • 相关阅读:
    在vscode中显示空格和tab符号
    如何正确理解关键字"with"与上下文管理器
    HADOOP基本操作命令
    Ganglia环境搭建并监控Hadoop分布式集群
    关于分布式系统的数据一致性问题
    hadoop snapshot 备份恢复 .
    hadoop主节点(NameNode)备份策略以及恢复方法
    HDFS snapshot操作实战
    从 secondarynamenode 中恢复 namenode
    hadoop 通过distcp进行并行复制
  • 原文地址:https://www.cnblogs.com/bear-blogs/p/9823184.html
Copyright © 2011-2022 走看看