Skip to content

Instantly share code, notes, and snippets.

@hoffination
Created December 21, 2016 04:57
Show Gist options
  • Save hoffination/3fc78ee172373a2af26fef963582c500 to your computer and use it in GitHub Desktop.
Save hoffination/3fc78ee172373a2af26fef963582c500 to your computer and use it in GitHub Desktop.
Dead Simple Event Aggregator
module.exports = (function() {
function EventManager() {
this.events = {};
}
// Will throw if there is no existing event to trigger
EventManager.prototype.trigger = function(msg) {
// grab all arguments passed after the first argument
var args = Array.prototype.splice.call(arguments, 1);
for (var i = 0, len = this.events[msg].length; i < len; i++) {
this.events[msg][i].apply(this, args);
}
};
EventManager.prototype.on = function(msg, func) {
if (!this.events[msg]) {
this.events[msg] = [];
}
this.events[msg].push(func);
};
EventManager.prototype.off = function(msg, func) {
for (var i = 0, len = this.events[msg].length; i < len; i++) {
if (this.events[msg][i] === func) {
this.events[msg].splice(i, 1);
}
}
};
return EventManager;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment