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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.