このパターンがどのように機能するかを完全に理解できるように、JavaScript で単純な pub/sub を実装しています。
//obj to hold references to all subscribers
pubSubCache = {};
//subscribe function - push the topic and function in to pubSubCache
subscribe = function (topic, fn) {
pubSubCache[topic] = fn;
};
//publish function
publish = function (topic, obj) {
var func;
console.log(obj);
console.log(pubSubCache);
// If topic is found in the cache
if (pubSubCache.hasOwnProperty(topic)) {
//Loop over the properties of the pubsub obj - the properties are functions
//for each of the funcitons subscribed to the topic - call that function and feed it the obj
for (func in pubSubCache[topic]) {
//this console.log returns a long list of functions - overloadsetter,overloadgetter,extend etc
//I expected to see the 'therapist' function here...
console.log(func);
//error occurs here - it should be calling the therapist function
pubSubCache[topic][func](obj);
}
}
};
function therapist (data) {
alert(data.response);
}
subscribe('patient/unhappy', therapist);
publish('patient/unhappy',{response:'Let me prescribe you some pills'})
</p>
私はほとんどそこにいますが、コードに奇妙な問題があるようです。パブリッシャー関数は、サブスクライバーへのすべての参照を保持するオブジェクトを検索し、一致するものを見つけます。次に、サブスクライブされている関数への参照を取得するために for in ループを実行しようとすると、必要な関数ではなく、この関数の長いリストが返されます。
overloadSetter overloadGetter 拡張 実装 非表示 保護 $family $constructor
私は当初、これらの関数は関数のプロトタイプからのものだと思っていましたが、そうではありません。
何か案は?これが理にかなっていることを願っています。