Skip to content

Instantly share code, notes, and snippets.

@flesch
Created August 18, 2012 15:32
Show Gist options
  • Save flesch/3387744 to your computer and use it in GitHub Desktop.
Save flesch/3387744 to your computer and use it in GitHub Desktop.
AS2 Event Dispatcher in JS
(function(window){
var EventDispatcher = window.EventDispatcher = function(scope){
this.scope = scope;
this.listeners = {};
};
EventDispatcher.prototype.addEventListener = function(type, listener){
if (listener instanceof Function) {
if(!this.listeners[type]) {
this.listeners[type] = [listener];
} else {
this.listeners[type].push(listener);
}
}
};
EventDispatcher.prototype.hasEventListener = function(type){
return (typeof this.listeners[type] != "undefined");
};
EventDispatcher.prototype.removeEventListener = function(type, listener){
if (this.hasEventListener(type)) {
var len = this.listeners[type].length, i = 0;
for (; i<len; i++) {
if (this.listeners[type][i] == listener) {
this.listeners.splice(i, 1);
}
}
}
};
EventDispatcher.prototype.dispatchEvent = function(type, args){
if (this.hasEventListener(type)) {
var len = this.listeners[type].length, i = 0;
for (; i<len; i++) {
this.listeners[type][i].apply(this.scope, [args]);
}
}
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment