观察者模式又叫发布订阅模式,它可以让多个观察者对象同时监听某一个主题对象,即在一个事件发生时,不同的对象迅速对其进行相应。就比如当又人闯红灯,不同的人对这件事迅速发起响应,当然这个比喻不太恰当,不过在团队开发中,每个人做自己不同的模块,那你在通过不去动其它人的代码或者说在不去看其他人的代码时怎么去将它们所要的事情做出来呢,这个时候就可以用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
总的来说,观察者模式可以在一个对象发生变化时,其它对象自动更新。