Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte calls new nested event handler on parent event call

I need to set up a new event handler for the window after a particular event occurs, so my component code is like this:

<script>
  const secondClick = () => {
   console.log(2);
  };

 const firstClick = () => {
  console.log(1);
 
  // waiting for the next click
  window.addEventListener("click",secondClick, {once: true});
 };
</script>

<button on:click={firstClick}> btn2 </button>

BUT if we click on the button the nested new window click handler is called immediately!

I’m baffled by such behavior. Could anyone put light on this and say how is this achievable without rolling to crunches on plain js.

Live demo on svelte REPL

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the button does not need to be able to fire the added handler, you can just stop the event propagation:

<button on:click|stopPropagation={firstClick}>

Otherwise you can also delay adding the handler, so the event bubbles up to the window first and then the handler is added. E.g.

setTimeout(() =>
     window.addEventListener("click", secondClick, { once: true })
);

Another approach is to just always add the handler and guard the code to be executed via a flag:

let armed = false;

function onWindowClick() {
  if (!armed)
    return;

  armed = false;
  // <logic here>
}

function onButtonClick() { setTimeout(() => armed = true); }
<svelte:window on:click={onWindowClick} />
...

This also ensures that the window click event handler is cleaned up when the component is destroyed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading