參看書籍JavaScript模式第七章設計模式
我的理解:觀察者模式又叫訂閱/發(fā)布模式崔步。被觀察者(發(fā)布者)內(nèi)部需要有一些東西來處理觀察者(訂閱者)的方法咽扇。
發(fā)布者對象paper 需要有以下這些成員:
1轴猎、subscribers:
??? 一個數(shù)組
//存儲每個事件類型下的訂閱者晴弃。每個類型下訂閱者是一個數(shù)組袱瓮。
2、subscribe():
??? 將訂閱者添加到subscribers數(shù)組
//訂閱者訂閱某個類型浮禾,傳入對應的回調(diào)函數(shù)交胚。
3、unsubscribe():
??? 從訂閱者數(shù)組subscribers刪除訂閱者盈电。
4蝴簇、publish():
??? 循環(huán)遍歷subscribers中的每個元素,并且調(diào)用他們注冊時所提供的方法匆帚。
5熬词、visitSubscribers()
??? 遍歷操作訂閱對象的方法。幫助方法卷扮。
如下:
發(fā)布者荡澎;
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);
}
}
}
}
}
創(chuàng)造一個發(fā)布者均践;
function makePublisher(o){
var i ;
for (i in publisher){
if(publisher.hasOwnProperty(i) && typeof publisher[i] === "function"){
o[i] = publisher[i];
}
}
o.subscribers = {
any:[]
}
}
發(fā)布者對象
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);
}
};
發(fā)布事件 和結果
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