Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, stop additional event listeners

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.

like image 793
Jack Sleight Avatar asked Jul 12 '09 00:07

Jack Sleight


People also ask

How do I get rid of added event listener?

JavaScript | removeEventListener() method with examples The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

Why is event listener firing multiple times?

This symptom is indicative that you've registered the same listener more than once. You must remember to deregister events when your component unloads to prevent his problem.

Can a button have 2 event listeners?

Can you have more than one event listener? We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

What happens if you add an event listener twice?

If the same event listener function is registered twice on the same node with the same type and useCapture arguments, the second registration is simply ignored. ...


1 Answers

The DOM Level 3 method event.stopImmediatePropagation is exactly what I need here. Unfortunately, it's not currently implemented in any browser (that I know of).

like image 84
Jack Sleight Avatar answered Oct 25 '22 12:10

Jack Sleight