Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created October 14, 2011 22:47
Show Gist options
  • Save ryanflorence/1288582 to your computer and use it in GitHub Desktop.
Save ryanflorence/1288582 to your computer and use it in GitHub Desktop.
Simple Pub/Sub
!function () {
var channels = {};
this.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
this.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
}.call(this);
subscribe('foo', function (a, b) {
console.log(a, b);
});
publish('foo', 1, 2);
@ryanflorence
Copy link
Author

Sorry for the original response, just re-read it and I sound like a jerk. Please forgive me.

You don't want to throw an error when you publish a channel with no subscriptions, you'd be throwing errors like crazy because you aren't always subscribing to everything. That's the beauty of pub sub, tell the world you're doing something, but don't require anybody to do anything with it, nor require every module to be operating properly. A module can fail, but it doesn't affect the rest of your app.

I still don't see the "errors I missed" nor do I see how your solution is simpler :\ How is a confusing ternary expression simpler than a quick if statement?

@nijikokun
Copy link

if statements require a variable to be instanced, the ternary solves that. your personal quip about the (||) is better than mine and simpler, I was simplifying the code to not instance variables.

The errors were not checking variables, that is up to the creator I suppose, you can exclude it, just a simple "protection" layer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment