Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  172] [ 5]  / answers: 1 / hits: 16361  / 15 Years ago, sun, july 12, 2009, 12:00:00

Imagine I have this code:



var myFunc1 = function(event) {
alert(1);
}
var myFunc2 = function(event) {
alert(2);
}

element.addEventListener('click', myFunc1);
element.addEventListener('click', myFunc2);


When the click event is fired myFunc1 is called, then myFunc2. But how do I (if at all possible) stop myFunc2 from being called if some condition in myFunc1 is met? event.stopPropagation() is not the solution, as this is not an event capturing/bubbling problem.



Thanks.


More From » events

 Answers
5

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.


[#99145] Tuesday, July 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;