![](/img/trans.png)
[英]my DIY trim function cannot return correct answer, it returns undefied
[英]My publisher does not return the subscribed function - DIY pub/sub implementation
我正在用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'})
我快到了,但是我的代碼似乎有一個奇怪的問題。 發布者功能搜索包含所有對訂閱者的引用的對象,並成功找到匹配項。 然后,當我嘗試在for in循環中獲取對所預訂功能的引用時,我會得到一長串功能列表,而不是想要的功能列表:
重載工具重載擴展器隱藏工具$ family $ constructor
我最初以為這些功能來自該功能的原型,但並非如此。
有任何想法嗎? 希望這是有道理的。
在您的訂閱中,您肯定要允許一個主題的多個訂閱。 因此,每個主題的緩存條目應為一個數組:
//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);
}
}
};
參見小提琴: http : //jsfiddle.net/cRTRL/1/
啊,看來這是一條紅鯡魚。 我看到返回的功能來自使用選定的mootools的jsfiddle測試的結果。 我看到的功能就是從那里開始的。
不幸的是,我的代碼雖然沒有固定,但是現在還沒有進入for in循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.