发布订阅模式

简单的发布订阅

// 发布者
let Release = function (){
  let listenerList = [];

  this.add = function (fn){
    listenerList.push(fn)
  }

  this.tigger = function(){
    listenerList.forEach((item) => {
      item();
    })
  }
}

let rel = new Release();
rel.add(function(){
  console.log("这个监听了很久了")
});

rel.tigger();

通用的发布订阅

var Event = (function(){
  let clientList = {},
      tigger,
      listen,
      remove;

  listen = function(key, fn){
     if(!clientList[key]){
       clientList[key] = [];
     }

     clientList[key].push(fn);
  }
  
  tigger = function(){
    let key  = Array.prototype.shift.apply(arguments);
    if(clientList[key] && clientList[key].length > 0){
      clientList[key].forEach(item => { 
        item.apply(this, arguments)
      })
    }
  }

  remove = function(key, fn){
    if(clientList[key] && clientList[key].length > 0){ 
      for (let index = 0; index < clientList[key].length; index++) {
        const item = clientList[key][index];
        if(item === fn){
          clientList[key].splice(index, 1);
        }
      }
    }
  }

  return {
    tigger,
    listen,
    remove
  }
}())

let like = function(){
  console.log("这个是我爱吃的东西")
}
let love = function(){
  console.log("这个是我最爱的人")
}

let activity = function () {
  console.log("这个是一个莫名其妙的活动")
}

Event.listen("test", like)
Event.listen("test", love)
Event.listen("ac", activity)


// 触发test部分的内容
console.log("触发test部分的内容") 
Event.tigger("test"); 

// 触发ac部分的内容
console.log("触发ac部分的内容") 
Event.tigger("ac");


console.log("移除test的like内容")
Event.remove("test", like);

console.log("继续触发test的内容")
Event.tigger("test")

不同的区域通讯

let a = (function(){ 
  let count = 0;
  let btnElement = document.getElementById("ObserverBtn");
  btnElement.onclick = function(){
    Event.tigger("clickTest", count++)
  };
})() 
let b = (function(){  
  let showElement = document.getElementById("show"); 
  Event.listen("clickTest", function(val){ 
    showElement.innerText = val;
  })
})()
posted on 2021-07-22 21:36  人生之外的路途  阅读(94)  评论(0编辑  收藏  举报