Skip to content

Instantly share code, notes, and snippets.

@carldanley
Last active December 21, 2015 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save carldanley/e5854fe87bfd607ad96c to your computer and use it in GitHub Desktop.
Save carldanley/e5854fe87bfd607ad96c to your computer and use it in GitHub Desktop.
Example of the Mediator pattern
var Mediator = ( function( window, undefined ) {
function Mediator() {
this._topics = {};
}
Mediator.prototype.subscribe = function mediatorSubscribe( topic, callback ) {
if( ! this._topics.hasOwnProperty( topic ) ) {
this._topics[ topic ] = [];
}
this._topics[ topic ].push( callback );
return true;
};
Mediator.prototype.unsubscribe = function mediatorUnsubscrive( topic, callback ) {
if( ! this._topics.hasOwnProperty( topic ) ) {
return false;
}
for( var i = 0, len = this._topics[ topic ].length; i < len; i++ ) {
if( this._topics[ topic ][ i ] === callback ) {
this._topics[ topic ].splice( i, 1 );
return true;
}
}
return false;
};
Mediator.prototype.publish = function mediatorPublish() {
var args = Array.prototype.slice.call( arguments );
var topic = args.shift();
if( ! this._topics.hasOwnProperty( topic ) ) {
return false;
}
for( var i = 0, len = this._topics[ topic ].length; i < len; i++ ) {
this._topics[ topic ][ i ].apply( undefined, args );
}
return true;
};
return Mediator;
} )( window );
// example subscriber function
var Subscriber = function ExampleSubscriber( myVariable ) {
console.log( myVariable );
};
// example usages
var myMediator = new Mediator();
myMediator.subscribe( 'some event', Subscriber );
myMediator.publish( 'some event', 'foo bar' ); // console logs "foo bar"
@graham-u
Copy link

graham-u commented Jan 3, 2015

Really useful, thanks.

You have a typo in unsubscribe method: "mediatorUnsubscrive"

@RobGraham
Copy link

Why are you using named functions for the prototype method names since they're already defined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment