Created
October 14, 2011 22:47
-
-
Save ryanflorence/1288582 to your computer and use it in GitHub Desktop.
Simple Pub/Sub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
subscribe('foo', function (a, b) { | |
console.log(a, b); | |
}); | |
publish('foo', 1, 2); |
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
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?