Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Created May 25, 2012 16:33
Show Gist options
  • Save mohamedmansour/2789079 to your computer and use it in GitHub Desktop.
Save mohamedmansour/2789079 to your computer and use it in GitHub Desktop.
JavaScript Mediator Pattern
Utils = {};
/**
* Mediator pattern based on previous work by @rpflorence, depends on underscore :)
*
* Subscribe to an event:
* Utils.mediator.subscribe('FOO', onFoo);
* function onFoo(data) {alert(data.bar);};
*
* Fire an event:
* Utils.mediator.publish('FOO', {bar: true});
*
* @license MIT
* @author Mohamed Mansour (http://mohamedmansour.com)
*/
Utils.mediator = (function() {
/**
* Subsribes to a channel and listens.
*
* @param {string} channel The channel to subscribe to.
* @param {function} callback The callback for the response of the subscription.
*/
var subscribe = function(channel, callback) {
if (!this.channels[channel]) this.channels[channel] = [];
this.channels[channel].push({ context: this, callback: callback });
return this;
},
/**
* Publishes to a channel with optional data.
*
* @param {string} channel The channel to publish data to.
* @param {...*} arguments Can publish any data.
*/
publish = function(channel) {
if (!this.channels[channel]) return false;
var args = Array.prototype.slice.call(arguments, 1);
_.each(this.channels[channel], function(subscription) {
subscription.callback.apply(subscription.context, args);
});
return this;
};
return {
channels: {},
subscribe: subscribe,
publish: publish
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment