这是一个难懂的模式···
/**
*观察者模式(发布-订阅模式):一种行为模式。
* 主要处理不同对象之间的交互通信问题。观察者模式中通常会包含两类对象。
* * 一个或多个发布者对象:当有重要的事情发生时,会通知订阅者
* * 一个或多个订阅者对象:它们追随一个或多个发布者,监听他们的通知,并作出相应的反应
*/
//以下是一个观察者对象的实现对象,其中包含了订阅相关的方法,并可以将任意对象转变为发布者,
var observer = {
addSubscriber:function (callback) {
if (typeof callback === "function"){
this.subscribers[this.subscribers.length] = callback;
}
},
removeSubscriber:function (callback) {
for (var i = 0;i< this.subscribers.length; i++){
if (this.subscribers[i] === callback){
delete this.subscribers[i];
}
}
},
publish:function (what) {
for (var i = 0;i < this.subscribers.length; i++){
if (typeof this.subscribers[i] === 'function'){
this.subscribers[i](what);
}
}
},
make:function (o) {
//turns an object into a publisher
for (var i in this){
if (this.hasOwnProperty(i)){
o[i] = this[i];
o.subscribers = [];
}
}
}
};
//下面创建一些订阅者。订阅者可以是任意对象,他们的唯一职责是在某些重要事件发生时调用publish()方法。
//下面是一个blogger对象,每当新博客准备好时,就会调用publish() 方法。
var blogger = {
writeBlogPost:function () {
var content = 'Today is'+ new Date();
this.publish(content);
}
};
//另有一个 la_times 对象,每当新一期的报刊出来时,就会调用publish() 方法。
var la_times= {
newIssue:function () {
var paper = 'Martians have landed on Earch!';
this.publish(paper);
}
}
//* 它们都很容易转变为发布者;
observer.make(blogger);
observer.make(la_times);
//与此同时,准备两个简单对象 jack 和 jill
var jack = {
read:function (what) {
console.log("I just read that" + what)
}
};
var jill = {
gossip:function (what) {
console.log("You didn't hear it form me,but"+what)
}
};
//他们可以订阅blogger对象,只需要提供事件发生时的回调函数
blogger.addSubscriber(jack.read);
blogger.addSubscriber(jill.gossip);
//当 blogger写了新的博客时,jack 和 jill 会收到通知
> blogger.writeBlogPost();
/*输出:
* I just read thatToday isTue Apr 10 2018 22:00:25 GMT+0800 (中国标准时间)
* You didn't hear it form me,butToday isTue Apr 10 2018 22:00:25 GMT+0800 (中国标准时间)
* */
// 任何时候jill 都可以取消订阅。当博主写了另一篇博客时,jill就不会再周到通知消息
blogger.removeSubscriber(jill.gossip());
> blogger.writeBlogPost();
/*输出:
* I just read thatToday isTue Apr 10 2018 22:00:25 GMT+0800 (中国标准时间)*/
//jill 也可以订阅LA Times,因为一个订阅者可以对应多个发布者
la_times.addSubscriber(jill.gossip);
//当LA Times 发行新的期刊后,jill 就会收到通知并执行 jill.gossip()方法
> la_times.newIssue();
// You didn't hear it from me,but Martians have landed on Earth!