Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Created November 21, 2010 02:35
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 sebmarkbage/708382 to your computer and use it in GitHub Desktop.
Save sebmarkbage/708382 to your computer and use it in GitHub Desktop.
Extends ART.Element with listen/ignore event subscriptions.
/*
---
name: ART.Events
description: "Extends ART.Element with listen/ignore event subscriptions."
requires: [ART/ART.Element, More/Table]
provides: [ART.Events]
...
*/
ART.Element.implement({
/* events */
listen: function(type, fn){
if (!this._events) this._events = {};
if (typeof type != 'string'){ // listen type / fn with object
for (var t in type) this.listen(t, type[t]);
} else { // listen to one
if (!this._events[type]) this._events[type] = new Table;
var events = this._events[type];
if (events.get(fn)) return this;
var bound = fn.bind(this);
events.set(fn, bound);
var element = this.element;
if (element.addEventListener) element.addEventListener(type, bound, false);
else element.attachEvent('on' + type, bound);
}
return this;
},
ignore: function(type, fn){
if (!this._events) return this;
if (typeof type != 'string'){ // ignore type / fn with object
for (var t in type) this.ignore(t, type[t]);
return this;
}
var events = this._events[type];
if (!events) return this;
if (fn == null){ // ignore every of type
events.each(function(fn, bound){
this.ignore(type, fn);
}, this);
} else { // ignore one
var bound = events.get(fn);
if (!bound) return this;
var element = this.element;
if (element.removeEventListener) element.removeEventListener(type, bound, false);
else element.detachEvent('on' + type, bound);
}
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment