There's a further problem: the order that event listeners are executed is undefined. You'll need to handle event dispatch on your own to get around this, which leads us to some variant of llimllib's suggestion.
function dispatchSleightEvent(evt) {
var listeners = evt.currentTarget.sleightListeners[evt.type];
// can't use for-in because enumeration order is implementation dependent
for (var i=0; i<listeners.length; ++i) {
if (listeners[i]) {
if (! listeners[i].call(evt.currentTarget, evt)) {
return false;
}
}
}
return true;
}
function mixinSleightTarget(obj) {
if (! obj.sleightListeners) {
obj.sleightListeners = {}
obj.addSleightListener = function(type, listener) {
if (!this.sleightListeners[type]) {
this.sleightListeners[type] = [];
this.addEventListener(type, dispatchSleightEvent);
}
if (!this.sleightListeners[type+listener] {
this.sleightListeners[type+listener] = this.sleightListeners[type].length;
this.sleightListeners[type].push(listener);
}
}
obj.removeSleightListener = function(type, listener) {
if (this.sleightListeners[type+listener] {
delete this.sleightListeners[type][this.sleightListeners[type+listener]];
delete this.sleightListeners[type+listener];
}
}
}
}
This code is completely untested. To stop event dispatch while on a single target, an event listener returns false
. If you want more data hiding, you can rewrite the above from a functional programming standpoint, though this might introduce memory leaks.