Skip to content

Instantly share code, notes, and snippets.

@edvakf
Created May 11, 2009 19: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 edvakf/110135 to your computer and use it in GitHub Desktop.
Save edvakf/110135 to your computer and use it in GitHub Desktop.
var EventGroup = function(target) {
this.target = target || window;
this.handlers = {};
this.doPreventDefault = true;
this.doStopPropagation = true;
var self = this;
this.delegate = function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement;
if (!e.stopPropatation) e.stopPropagation = function() {this.cancelBubble = true};
if (!e.preventDefault) e.preventDefault = function() {this.returnValue = false};
if (this.doPreventDefault) e.preventDefault();
if (this.doStopPropagation) e.stopPropagation();
var handlers = self.handlers[e.type];
if (handlers) {
for (var i = 0; i < handlers.length; i++) handlers[i].call(self, e);
}
}
return this;
}
EventGroup.prototype.listen = function(type, func) {
var target = this.target;
var handlers = this.handlers[type];
if (handlers) {
for (var i = 0; i < handlers.length; i++) if (handlers[i] === func) break;
if (i == handlers.length) handlers.push(func);
} else {
this.handlers[type] = [func];
if (target.addEventListener) {
target.addEventListener(type, this.delegate, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, this.delegate);
} else {
target['on' + type] = this.delegate;
}
}
return this;
};
EventGroup.prototype.unlisten = function(type, func) {
var target = this.target;
var handlers = this.handlers[type];
if (handlers && func) {
for (var i = 0; i < handlers.length; i++) {
if (handlers[i] === func) {
handlers.splice(i, 1);
break;
}
}
if (handlers.length) return this;
}
handlers = null;
if (target.removeEventListener) {
target.removeEventListener(type, this.delegate, false);
} else if (target.detachEvent) {
target.detachEvent('on' + type, this.delegate);
} else {
target['on' + type] = null;
}
return this;
};
EventGroup.prototype.destroy = function(type) {
for (var type in this.handlers) if (this.handlers.hasOwnProperty(type)) {
this.unlisten(type);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment