Skip to content

Instantly share code, notes, and snippets.

@mpjura mpjura/mediator.js
Last active Dec 14, 2015

Embed
What would you like to do?
Mediator Mixin
var Mediator = {
channels: {},
subscribe: function( channel, fn, ctx ){
var channels = this.channels;
if ( !channels[ channel ] ){ channels[ channel ] = []; }
channels[ channel ].push({ context: ctx || this, callback: fn });
return this;
},
unsubscribe: function( channel, fn ){
var channels = this.channels,
sub;
if ( !channels[ channel ] ){ return false; }
for ( var i = 0, len = channels[ channel ].length; i < len; i++ ){
sub = channels[ channel ][ i ];
if ( sub.callback === fn ){
channels[ channel ].splice(i, 1);
if ( channels[ channel].length < 1 ){
delete channels[ channel ];
}
}
}
return this;
},
publish: function( channel ){
var channels = this.channels,
args = Array.prototype.slice.call( arguments, 1 ),
sub;
if ( !channels[ channel ] ){ return false; }
for ( var i = 0, len = channels[ channel ].length; i < len; i++ ){
sub = channels[ channel ][ i ];
sub.callback.apply( sub.context, args );
}
return this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.