觀察者模式(訂閱發佈模式)
該模式廣泛應用於客戶端程序,促進鬆散耦合
var publisher = {
subsribers: {
any: []
},
subscribe: function (fn,type) {
type = type || 'any';
if(!this.subscribers[type]){
this.subscribers[type] = [];
}
this.subscribers[type] = fn;
},
unsubscribe: function (fn,type) {
this.visitSubscribers('unsubscribe',fn,type);
},
publish: function (fn,type) {
this.visitSubscribers('publish',fn,type);
},
visitSubscribers: function (action,arg,type) {
var pubtype = type || 'any',
subscribers = this.subscribers[pubtype],
I,
max = subscribers.length;
for(I = 0;i < max;i ++ ){
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)){
o[i] = publisher[I];
}
}
o.subscribers = {any: []};
}
Var paper = {
daily: function () {
this.publish('big news today');
},
monthly: function () {
this.publish('interesting analysis','monthly')
}
};
makePublisher(paper);
Var Joe = {
drinkCoffee: function (paper) {
console.log('Just read ' + paper)
},
sundayPreNap: function (paper) {
console.log('About to fall asleep reading this ' + paper);
}
};
Publisher.subscribe(Joe.drinkCoffee);
Publisher.subscribe(Joe.sundayPreNap,'monthly');
Publisher.daily();
Publisher.daily();
Publisher.daily();
Publisher.monthly();
>Just read big news today
>Just read big news today
>Just read big news today
>About to fall asleep reading this interesting analysis
makePubliser(Joe);
Joe.tweet = function (msg) {
this.publish(msg);
}
Paper.readTweets = function (tweet) {
alert('Call big meeting someone ' + tweet);
}
Joe.subscribe(paper.readTweets);
Joe.tweet('hated the paper today');
>Call big meeting someone hated the paper today