Skip to content

Instantly share code, notes, and snippets.

@shov
Last active April 17, 2017 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shov/c0b627d31dc9d443eb7a3c68c6b69817 to your computer and use it in GitHub Desktop.
Save shov/c0b627d31dc9d443eb7a3c68c6b69817 to your computer and use it in GitHub Desktop.
Event Controller
(function(global){
function EventController(){
var oEvents = {};
this.doEvent = function(eventname, args) {
if(typeof(eventname) !== 'string') {
return false;
}
if(typeof(oEvents[eventname]) === 'object' && Array.isArray(oEvents[eventname])) {
var aResults = {};
oEvents[eventname].forEach(function(handler, i){
if(typeof(handler) === 'function') {
if(typeof(args) !== 'undefined') {
aResults[i] = handler(args);
} else {
aResults[i] = handler();
}
}
});
return aResults;
}
return false;
}
this.addListener = function(eventname, callback) {
if(typeof(eventname) !== 'string' || typeof(callback) != 'function') {
return false;
}
if(typeof(oEvents[eventname]) === 'object' && Array.isArray(oEvents[eventname])) {
oEvents[eventname].push(callback);
return true;
}
if(typeof(oEvents[eventname]) === 'undefined') {
oEvents[eventname] = [callback];
return true;
}
return false;
}
}
if(typeof(global.eventController) === 'undefined') {
global.eventController = new EventController();
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment