Search code examples
svelteweb-componentcustom-element

How to properly remove event listener from window object?


CustomElement.svelte

<svelte:options tag="custom-element" />

<script>
  import { onMount, onDestroy } from "svelte";

  onMount(() => {
    window.addEventListener("scroll", funcRef);
  });

  onDestroy(() => {
    window.removeEventListener("scroll", funcRef);
  });

  const funcRef = (event) => {
    doWhatever();
  }
</script>

Actually, the event handler should be removed when the custom element gets removed from the document, but it won't. What am I missing?


Solution

  • Getting removed from the document is not the same as getting destroyed. The code of this component should work as intended.

    If you use the client-side API or the component lives outside of Svelte's logic (i.e. is not added/removed by another Svelte component, e.g. via {#if}), you have to make sure to actually call $destroy.