Skip to content

Instantly share code, notes, and snippets.

@FiNGAHOLiC
Created January 16, 2012 06:15
Show Gist options
  • Select an option

  • Save FiNGAHOLiC/1619358 to your computer and use it in GitHub Desktop.

Select an option

Save FiNGAHOLiC/1619358 to your computer and use it in GitHub Desktop.
Mediator Pattern
// http://shichuan.github.com/javascript-patterns/
var mediator = (functuion(){
var subscribe = function(channel, fn){
if(!mediator.channels[channel]) mediator.channels[channel] = [];
mediator.channels[channel].push({ context : this, callback : fn });
return this;
};
var 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;
}
};
}());
mediator.name = 'tim';
mediator.subscribe('nameChange', function(arg){
console.log(this.name);
this.name = arg;
console.log(this.name);
});
madiator.publish('nameChange', 'david');
var obj = { name : 'sam' };
mediator.installTo(obj);
obj.subscribe('nameChange', function(arg){
console.log(this.name);
this.name = arg;
console.log(this.name);
});
obj.publish('nameChange', 'john');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment