Ripper
Ripper

Reputation: 127

How to cancel next event calls?

I have an event "pointerdown" but I want it to cancel the event call when a certain condition is met in one of the callbacks. So, all the next callbacks should not be called.

I have tried evt.preventDefault(); but that does not work, I have also tried evt.stopPropagation(); but that does not work.

const pointer = getMousePos(evt);
if (inBounds(pointer)) {
    evt.preventDefault();
    evt.stopPropagation();
}

The inBounds function returns true as expected, but the next callbacks of the event are still called. This event is added first, before the other events I wish to cancel but they are not.

Upvotes: 0

Views: 1124

Answers (2)

EmeraldCoder
EmeraldCoder

Reputation: 547

If your listeners are attached on the same element, you will need to use stopImmediatePropagation() instead of stopPropagation()

The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called.

If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation

You can also find a little description of the difference between both methods here: stopPropagation vs. stopImmediatePropagation

Here a little demonstration of how you can use it. In this case, the second listener will never be called when the counter is a even number.

let counter = 0

const button = document.getElementById('TheButton')

button.addEventListener('click', e => {
  counter++
  
  console.log(`first listener: ${counter}`)
  
  if (counter % 2 === 0) e.stopImmediatePropagation()
})

button.addEventListener('click', e => {
  console.log(`second listener: ${counter}`)
})
<button id="TheButton">
OK
</button>

Upvotes: 3

Barmar
Barmar

Reputation: 780851

Use a global variable that you toggle to indicate whether the other event code should run.

let doBFunction = true;
element.addEventListener("pointerdown", function(evt) {
    const pointer = getMousePos(evt);
    if (inBounds(pointer)) {
        doBFunction = false;
    } else {
        doBFunction = true;
    }
    // rest of code
});
element.addEventListner("pointerdown", function(evt) {
    if (!doBfunction) {
        return;
    }
    // rest of code
});

Upvotes: 0

Related Questions