Created
December 21, 2016 04:57
-
-
Save hoffination/3fc78ee172373a2af26fef963582c500 to your computer and use it in GitHub Desktop.
Dead Simple Event Aggregator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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