Created
March 26, 2016 12:11
-
-
Save kopiro/0e557132f9d0cb0473b9 to your computer and use it in GitHub Desktop.
Simple event aggregator
This file contains hidden or 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
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