0
votes

I found a strange behaviour, if I add document.addEventListener to click on onMount.

  1. I have 2 components: App and Nested
  2. There is a button in App, which sets isShow = true, and Nested component shows.
  3. In Nested component there is onMount where runs document.addEventListener('click')
  4. If I click on button in App, Nested component will be mounted, event listener immediately will be attached to document, and click, which was clicked before component mount, will be processed.

I guess it happens because Svelte does it in one tick. I tried await tick(), but it didn't help.

I see one of solution is wrap document.addEventListener to setTimeout. It works, but I think it is bad decision.

So, is it behaviour normal or is it a bug?

Here is an example: https://svelte.dev/repl/c89c272ca6c245dabf8451ba950d10c0?version=3.6.8

1

1 Answers

3
votes

This is expected behaviour. The simplest solution is probably to add { capture: true } (or just true) as the third argument to addEventListener and removeEventListener: https://svelte.dev/repl/daee8509d6634a68b2cf35e53f660e34?version=3.6.8. This works because the event has left the capturing phase by the time the nested event listener is attached, and is now in the bubbling phase.