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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM