Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow callers of publish() to see how many subscribers were notified. #4

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
27 changes: 25 additions & 2 deletions pubsub.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@
;(function(d){

// the topic/subscription hash
var cache = {};
var cache = {},
options = {};

d.publish = function(/* String */topic, /* Array? */args){
d.pubsubOptions = function(/* String */optionName, /* object */optionValue) {
options[optionName] = optionValue;
}

d.publish = function(/* String */topic, /* Array? */args, /* bool */mustHaveSubscribers){
// summary:
// Publish some data on a named topic.
// topic: String
Expand All @@ -28,9 +33,27 @@
// with a function signature like: function(a,b,c){ ... }
//
// | $.publish("/some/topic", ["a","b","c"]);
var subscribers = 0,
errorMessage;
cache[topic] && d.each(cache[topic], function(){
this.apply(d, args || []);
subscribers += 1;
});

if (subscribers === 0 && (mustHaveSubscribers || options.mustHaveSubscribers || (typeof options.onNoSubscribers === "function"))) {
if (typeof options.onNoSubscribers === "function") {
options.onNoSubscribers(topic);
} else {
errorMessage = 'The topic "'+ topic +'" was published when there were no subscribers to the topic.';
if (typeof console !== "undefined") {
console.error(errorMessage);
} else {
alert(errorMessage);
}
}
}

return subscribers;
};

d.subscribe = function(/* String */topic, /* Function */callback){
Expand Down