Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created March 26, 2016 12:11
Show Gist options
  • Save kopiro/0e557132f9d0cb0473b9 to your computer and use it in GitHub Desktop.
Save kopiro/0e557132f9d0cb0473b9 to your computer and use it in GitHub Desktop.
Simple event aggregator
var EventAggregator = function() {
this._events = {};
};
EventAggregator.prototype.trigger = function (msg) {
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);
}
};
EventAggregator.prototype.on = function (msg, func) {
this._events[msg] = this._events[msg] || [];
this._events[msg].push(func);
};
EventAggregator.prototype.off = function (msg, func) {
if (func == null) {
this._events[msg] = [];
} else {
for (var i = 0, len = (this._events[msg] || []).length; i < len; i++) {
if (this._events[msg][i] === func) {
this._events[msg].splice(i, 1);
}
}
}
};
module.exports = new EventAggregator();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment