Reputation: 10746
I'm implementing a simple pub/sub in javascript to help me fully understand how this pattern works:
//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'})
I'm almost there but seem to have a strange problem in my code. The publisher function searches through the object that holds all the references to the subscribers and successfully finds a match. Then when I try to do a for in loop to get a reference to the function that is subscribed I get back this long list of functions instead of the function I want:
overloadSetter overloadGetter extend implement hide protect $family $constructor
I initially thought these functions were from the prototype of the function but they are not.
Any ideas? Hope this makes sense.
Upvotes: 0
Views: 83
Reputation: 16033
In your subscribe, you surely want to allow for multiple subscriptions to a topic. The cache entry for each topic should therefor be an array :
//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);
};
In publish, you need to call EACH of the functions in the topic cache :
//publish function
publish = function (topic, obj) {
if (pubSubCache.hasOwnProperty (topic)) {
for (var f = pubSubCache[topic].length; f--;) {
pubSubCache[topic][f](obj);
}
}
};
See the fiddle : http://jsfiddle.net/cRTRL/1/
Upvotes: 1
Reputation: 10746
Ah it seems this was a red-herring. The functions I was seeing returned were from a result of testing using jsfiddle with mootools selected. The functions I was seeing were from there.
Unfortunately my code is not fixed though.....not getting in to the for in loop at all now.
Upvotes: 0