pubsub pattern | pub sub publish subscribe js
function bar( d ) {
console.log( "Bar: "+d );
};
function baz( d ) {
console.log( "Baz: "+d );
};
var pubsub = {
// Published events and their subscribed functions
events: {},
// Add event name to list
publish: function( eventName ) {
this.events[eventName] = [];
return;
},
// Remove event name from list
unpublish: function( eventName ) {
delete this.events[eventName];
return;
},
// Subscribe function to event
subscribe: function( eventName , callbackfunction ) {
this.events[eventName].push( callbackfunction );
return;
},
// Remove function from event
unsubscribe: function( eventName , callbackfunction ) {
this.events[eventName].splice( this.events[eventName].indexOf( callbackfunction ) , 1 );
return;
},
// Initiate event
emit: function( eventName , data ) {
if( this.events[eventName] ) {
this.events[eventName].forEach(function(fn){
fn(data);
});
} else {
console.error("Event \""+eventName+"\" has not beed published");
}
}
};
// Publish an event
pubsub.publish( "foo" );
// Subscribe functions to event
pubsub.subscribe( "foo" , bar );
pubsub.subscribe( "foo" , baz );
console.log( pubsub.events );
// Init event and send data
pubsub.emit( "foo" , 5 );
/*
pubsub.unsubscribe( "foo" , bar );
pubsub.emit( "foo" , 5 );
pubsub.unpublish( "foo" );
console.log( pubsub.events );
*/