我正在用 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 循环以获取对订阅的函数的引用时,我得到了这个长长的函数列表,而不是我想要的函数:
重载Setter 重载Getter 扩展实现隐藏保护$family $constructor
我最初认为这些函数来自函数的原型,但事实并非如此。
有任何想法吗?希望这是有道理的。