Javascript 我的发布者不返回订阅的函数-DIY发布/订阅实现
我正在用javascript实现一个简单的pub/sub,以帮助我完全理解此模式的工作原理:Javascript 我的发布者不返回订阅的函数-DIY发布/订阅实现,javascript,design-patterns,Javascript,Design Patterns,我正在用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; }; //p
//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'})
我就快到了,但代码中似乎有一个奇怪的问题。publisher函数搜索包含对订阅者的所有引用的对象,并成功找到匹配项。然后,当我尝试执行for in循环以获取对已订阅函数的引用时,我会返回一长串函数,而不是我想要的函数:
过载设定器
超吸气剂
延伸
实施
隐藏
保护
$family
$constructor
我最初认为这些函数来自函数的原型,但事实并非如此
有什么想法吗?希望这是有道理的。啊,这似乎是在转移注意力。我看到返回的函数是使用JSFIDLE和选定的mootools进行测试的结果。我看到的功能就在那里
不幸的是,我的代码不是固定的……现在根本没有进入for-in循环。在订阅中,您肯定希望允许对一个主题进行多个订阅。因此,每个主题的缓存项应为一个数组:
//subscribe function - push the topic and function in to pubSubCache
subscribe = function (topic, fn) { // if new topic init to empty array
if (!pubSubCache.hasOwnProperty (topic))
pubSubCache[topic] = [];
pubSubCache[topic].push (fn);
};
在发布中,您需要调用主题缓存中的每个函数:
//publish function
publish = function (topic, obj) {
if (pubSubCache.hasOwnProperty (topic)) {
for (var f = pubSubCache[topic].length; f--;) {
pubSubCache[topic][f](obj);
}
}
};
看小提琴: