淺談js觀察者模式


觀察者模式又叫發布訂閱模式,它可以讓多個觀察者對象同時監聽某一個主題對象,即在一個事件發生時,不同的對象迅速對其進行相應。就比如當又人闖紅燈,不同的人對這件事迅速發起響應,當然這個比喻不太恰當,不過在團隊開發中,每個人做自己不同的模塊,那你在通過不去動其它人的代碼或者說在不去看其他人的代碼時怎么去將它們所要的事情做出來呢,這個時候就可以用da到觀察者模式了。前面我們說過了單例對象,這里的觀察者其實我們也可以只用一個對象,並且這個對象的功能不需要更改。

首先我們定義一個對象,這個對象包括3個方法,注冊,發布,還有解除,注冊就是把觸發我事件的信號加載到數據對象中去,發布就是去觸發這個信號,解除就是把某個事件從我的事件庫中刪除。

var mapleTao={
  message:{},
  //注冊
  register:function(type,fn){
  if(this.message[type]){
    this.message[type].push(fn);
  }else{
    this.message[type]=[fn];
  }
  },
//發布
  fire:function(type,opt){
    if(!this.message[type]) return false;
    this.message[type].forEach(function(item){
      item(opt);
    });
  },
  //取消
  remove:function(type,fn){
    var i=this.message[type].indexOf(fn);
    if(!this.message[type]||i==-1) return false;
    this.message[type].splice(i,1);
  }
};

上述就是創建了一個觀察者對象,接下來就是對其簡單調用了。

(function(){
  var maple=function(){
    console.log("i am maple");
  }
  //注冊事件introduce
  mapleTao.register("introduce",maple);
})();
(function(){
  var tao=function(){
    console.log("i am tao");
  }
  //注冊事件introduce
  mapleTao.register("introduce",tao);
    setTimeout(function(){
  mapleTao.remove("introduce",tao); //introduce在事件庫中去除tao
    mapleTao.fire("introduce");      //觸發introduce信號 結果為i am maple
  },0)
})();

mapleTao.fire("introduce"); //觸發introduce信號 結果為i am maple,i am tao

(function(){
  var maple=function(obj){ //對參數處理
    console.log("i am maple,i am "+obj.status);
  }
//注冊事件status
  mapleTao.register("status",maple);
})();
(function(){
  var tao=function(obj){
    console.log("i am tao,i am "+obj.name);
}
//注冊事件status
  mapleTao.register("status",tao);
})();

mapleTao.fire("status",{status:"working",name:"studying"}); //結果 i am maple,i am working   i am tao,i am studying

總的來說,觀察者模式可以在一個對象發生變化時,其它對象自動更新。


免責聲明!

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



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