How to properly remove event listener from window object?

Viewed 195

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?

2 Answers

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.

the code you provided will work properly and it will automatically remove event listeners when the component is destroyed but here is a better version

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

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

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

    return ()=>{
      // this function is called when the component is destroyed
      window.removeEventListener("scroll", funcRef);
    }
  });
</script>
Related