Created
April 22, 2016 14:40
-
-
Save sketchpunk/7686ab1e10bb96b2a7609b0358b29d9a to your computer and use it in GitHub Desktop.
Object that handles custom events in Javascript
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
/*EXAMPLE CODE | |
var tObj = {val:"woot",func:function(){ console.log(this.val); console.log(arguments); }} | |
var evt = new EventManager("onprogress","oncomplete"); | |
evt.addEventListener("onprogress",function(){ console.log(arguments); }); | |
evt.addEventListenerDelegate("onprogress",tObj,tObj.func); | |
evt.dispatchEvent("onprogress",[1,3]); | |
*/ | |
var EventManager = function(){ | |
this.Handlers = {}; | |
for(var i=0; i < arguments.length; i+=1) this.Handlers[arguments[i]] = []; | |
};//func | |
EventManager.prototype.addEventListener = function(evtName,funcHandler){ | |
if(this.Handlers[evtName] === undefined) return false; | |
this.Handlers[evtName].push(funcHandler); | |
return true; | |
};//func | |
EventManager.prototype.addEventListenerDelegate = function(evtName,objRef,funcHandler){ | |
if(this.Handlers[evtName] === undefined) return false; | |
this.Handlers[evtName].push(function(){ funcHandler.apply(objRef,arguments); }); | |
return true; | |
};//func | |
EventManager.prototype.dispatchEvent = function(evtName,ary){ | |
for(var i = 0; i < this.Handlers[evtName].length; i++){ | |
try{ | |
this.Handlers[evtName][i].apply(this,ary); | |
}catch(err){ | |
console.log("error dispatching event"); | |
console.log(err); | |
}//try | |
}//for | |
};//func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment