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.
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.