参看书籍JavaScript模式第七章设计模式
我的理解:观察者模式又叫订阅/发布模式。被观察者(发布者)内部需要有一些东西来处理观察者(订阅者)的方法。
发布者对象paper 需要有以下这些成员:
1、subscribers:
一个数组
//存储每个事件类型下的订阅者。每个类型下订阅者是一个数组。
2、subscribe():
将订阅者添加到subscribers数组
//订阅者订阅某个类型,传入对应的回调函数。
3、unsubscribe():
从订阅者数组subscribers删除订阅者。
4、publish():
循环遍历subscribers中的每个元素,并且调用他们注册时所提供的方法。
5、visitSubscribers()
遍历操作订阅对象的方法。帮助方法。
如下:
发布者;
var publisher = {
subscribers: {
any: [] //事件类型:订阅者
},
subscribe: function(fn, type){
type = type || "any";
if (typeof this.subscribers[type] === "undefined"){
this.subscribers[type] = []
};
this.subscribers[type].push(fn);
},
unsubscribe: function(fn,type){
this.visitSubscribers('unsubscribe',fn,type);
},
publish: function(publication, type){
this.visitSubscribers('publish',publication,type);
},
visitSubscribers: function (action, arg, type){
var pubtype = type || 'any',
subscribers = this.subscribers[pubtype],
i,
max = subscribers.length;
for(i = 0;i < max; i += 1){
if(action === 'publish'){
subscribers[i](arg);
}else {
if (subscribers[i] === arg){
subscribers.splice(i, 1);
}
}
}
}
}
创造一个发布者;
function makePublisher(o){
var i ;
for (i in publisher){
if(publisher.hasOwnProperty(i) && typeof publisher[i] === "function"){
o[i] = publisher[i];
}
}
o.subscribers = {
any:[]
}
}
发布者对象
var paper = {
daily:function(){
this.publish("bing news today");
},
monthly: function(){
this.publish("interesting analysis", "monthly");
},
aha: function(){
this.publish("aha","monday");
}
};
makePublisher(paper);
订阅者对象
var joe = {
drinkCoffee: function (paper){
console.log("Just read" + paper);
},
sundayPreNap: function (monthly){
console.log('About to fall asleep reading this'+ monthly);
}
};
发布事件 和结果
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.sundayPreNap, 'monthly');
paper.subscribe(joe.sundayPreNap, 'monday');
paper.daily();//Just readbing news today
paper.daily();//Just readbing news today
paper.daily();//Just readbing news today
paper.monthly();//About to fall asleep reading thisinteresting analysis
paper.aha();//About to fall asleep reading thisaha