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);
@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