我正在努力理解可观察的/观察者的设计模式。
这是我到目前为止拥有的代码( Javascript模式书中的代码):
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*
我添加了一个发布对象来保存发布函数中的发布。我还检查发布类型是否有订阅者,如果没有,则调用return。现在,我需要弄清楚如何通知他们的旧出版物的订阅。
*编辑2*
新版本的工作脚本添加。这样做是正确的还是最好的方法?
发布于 2011-07-26 01:57:47
如果希望允许订阅者在发送通知后获得通知,则只需
对于每种不同的发布类型,
publication
添加到适当的列表中)2.1也许您还应该创建一个单独的send_notification_to(arg, type, subscriber)
方法,以避免与send_notification_to(arg, type, subscriber)
的代码重复
https://stackoverflow.com/questions/6824034
复制相似问题