Skip to content

Instantly share code, notes, and snippets.

@afreeland
Last active December 14, 2015 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afreeland/5100980 to your computer and use it in GitHub Desktop.
Save afreeland/5100980 to your computer and use it in GitHub Desktop.
JavaScript: Pub/Sub Mediator Pattern
window.mediator = (function(){
var subscribe = function(channel, fn, _context){
_context = (typeof _context != 'undefined') ? _context : this;
if (!mediator.channels[channel]) mediator.channels[channel] = [];
mediator.channels[channel].push({ context: _context, callback: fn });
return _context;
},
publish = function(channel){
if (!mediator.channels[channel]) return false;
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = mediator.channels[channel].length; i < l; i++) {
var subscription = mediator.channels[channel][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
channels: {},
publish: publish,
subscribe: subscribe,
installTo: function(obj){
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment