我正在尝试理解Observable / Observer设计模式。
这是我到目前为止的代码(来自Javascript Patterns的代码):
var publisher = {
subscribers: {
any: [] // event type: subscribers
},
publications: {
any: []
},
subscribe: function (fn, type) {
type = type || 'any';
if (typeof this.subscribers[type] === "undefined") {
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
if(typeof this.publications[type] === "undefined"){
return;
}
var pubs = this.publications[type],
i,
max = pubs.length
for(i = 0;i<max;i++){
this.subscribers[type][i](pubs[i]);
}
},
unsubscribe: function (fn, type) {
this.visitSubscribers('unsubscribe', fn, type);
},
publish: function (publication, type) {
var pubtype = type || 'any';
this.visitSubscribers('publish', publication, type);
if(typeof this.publications[pubtype] === "undefined") {
this.publications[pubtype] = [];
}
this.publications[pubtype].push(publication);
},
visitSubscribers: function (action, arg, type) {
var pubtype = type || 'any',
subscribers = this.subscribers[pubtype],
i,
max;
if(typeof subscribers === 'undefined') {
return;
}
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: []};
o.publications = {any: []};
}
var paper = {
daily: function () {
this.publish("big news today");
},
monthly: function () {
this.publish("interesting analysis", "monthly");
},
yearly: function () {
this.publish("every year","yearly");
}
};
makePublisher(paper);
var joe = {
drinkCoffee: function (paper) {
console.log('Just read ' + paper);
},
sundayPreNap: function (monthly) {
console.log('About to fall asleep reading this ' + monthly);
},
onHolidays: function(yearly) {
console.log('Holidays!'+yearly);
}
};
paper.daily();
paper.monthly();
paper.yearly();
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.onHolidays,'yearly');
paper.subscribe(joe.sundayPreNap, 'monthly');
我想知道是否有可能允许客户端接收通知 即使他们在之后注册了这些通知,也是。
我应该修改publisher.subscribe并检查是否未定义,是否发布事件类型?
提前致谢。
* 编辑1 *
我添加了一个publication对象来保存发布功能中的出版物。我还检查是否有发布类型的订阅者,如果没有,我会调用return。现在我需要弄清楚如何在订阅时通知他们旧版本。
* 编辑2 *
添加了新版本的工作脚本。它被认为是正确的还是最好的方法呢?
答案 0 :(得分:1)
如果您希望订阅者在发送后收到通知,您只需要
对于每种不同的发布类型,请保留您为其获取的所有通知的列表。
(发布时,将publication
添加到相应的列表中)
更改订阅功能,以便它还将所有相应的存储通知发送给迟到的订阅者。
2.1也许你还应该创建一个单独的send_notification_to(arg, type, subscriber)
方法,以避免代码重复visitSubscribers