Created
October 15, 2011 20:07
-
-
Save ryanflorence/1290072 to your computer and use it in GitHub Desktop.
Localized Pub Sub
This file contains hidden or 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
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; | |
}; |
This file contains hidden or 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
// 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