Observable/Observerデザインパターンを理解しようとしています。公開後の通知への公開/登録
これは私が持っているコード、これまで(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を変更して未定義の場合はチェックし、はいの場合はイベントタイプを公開する必要がありますか?
ありがとうございます。
* EDIT 1 *
私は出版物が発行する機能で出版物を保存するためにオブジェクトを追加しました。私はまた、パブリケーションタイプのサブスクライバがあるかどうかをチェックし、そうでない場合はリターンを呼び出します。今、私は購読している古い出版物のためにそれらを通知する方法を理解する必要があります。作業スクリプトの
* EDIT 2 *
新しいバージョンが追加されました。それが正しいと思っているのですか、それとも最善の方法ですか?
でコードduplicatioを避けるために、別々の
send_notification_to(arg, type, subscriber)
メソッドを作成する必要があります。それは正しい方法ですか?私は今、第二のステップを理解しようとしています。問題は、paper.yearly()が呼び出されたときです。これはpublisher.publishを呼び出しますが、サブスクライバーがないので未定義を返します。おそらく、このタイプのサブスクライバがあれば、公開方法をチェックする必要がありますか?本当に混乱しています... – chchristあなたのスクリプトは私のために働いているようです... – hugomg