我用JavaScript實現一個簡單的pub/sub來幫助我充分了解這種模式的工作原理:我的出版商不會返回訂閱功能 - DIY的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'})
我幾乎在那裏,但在我的代碼中似乎有一個奇怪的問題。發佈者函數搜索包含對訂閱者的所有引用併成功找到匹配項的對象。然後,當我試圖在循環做了去那所預訂的函數的引用我回來這麼久的功能,而不是功能列表我想:
overloadSetter overloadGetter 延長 實施 隱藏 保護 $ family $構造函數
我最初認爲這些函數來自函數的原型,但它們不是。
任何想法?希望這是有道理的。