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.
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 :
In publish, you need to call EACH of the functions in the topic cache :
See the fiddle : http://jsfiddle.net/cRTRL/1/