Skip to content

Instantly share code, notes, and snippets.

@csclyde
Created November 15, 2017 06:48
Show Gist options
  • Select an option

  • Save csclyde/4621e4cc8530e28f436a5d0687d6cc12 to your computer and use it in GitHub Desktop.

Select an option

Save csclyde/4621e4cc8530e28f436a5d0687d6cc12 to your computer and use it in GitHub Desktop.
EventRouter = function() {
this.events = {};
}
EventRouter.prototype.subscribe = function(eventName, callback, context) {
if(!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push({func: callback, ctx: context});
};
EventRouter.prototype.publish = function(eventName, parameters) {
if(!this.events[eventName]) {
console.log('Event published with no lsiteners: ' + eventName);
return;
}
this.events[eventName].forEach(function(el) {
el.func.apply(el.ctx, [parameters || {}]);
});
};
EventRouter.prototype.unsubscribe = function(eventName, callback) {
if(!this.events[eventName]){
return;
}
//filter out the method to be removed
this.events[eventName] = this.events[eventName].filter(function(el) {
return el !== callback;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment