Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created October 15, 2011 20:07
Show Gist options
  • Save ryanflorence/1290072 to your computer and use it in GitHub Desktop.
Save ryanflorence/1290072 to your computer and use it in GitHub Desktop.
Localized Pub Sub
var mediator = function (obj) {
var channels = {};
if (!obj) obj = {};
obj.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
obj.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);
}
};
return obj;
};
// make mediator a mediator itself
mediator(mediator);
mediator.subscribe('foo', function (a, b) {
console.log(a, b);
});
mediator.publish('foo', 1, 2);
// get a generic mediator with its own channels
var pubsub = mediator();
pubsub.subscribe;
pubsub.publish;
// or turn anything into a mediator
mediator(window);
publish;
subscribe;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment