Svelte

svelte/window-events

Listen to window and document events with svelte:window and svelte:document, not addEventListener in $effect or onMount.

drobnastatycznefe-svelte

Dlaczego

A listener added by hand in onMount or $effect has to be removed by hand; forgetting the cleanup leaves handlers firing after the component is gone and doubles them when it comes back. The special elements add and remove the listener with the component and are safe in server rendering.

Poprawka

<svelte:window onkeydown={onKey} />, <svelte:document onvisibilitychange={sync} />, and bind:innerWidth, bind:scrollY or bind:online on <svelte:window> for the common values. For an element listener that needs options, use an attachment ({@attach}) that returns its cleanup.

Przykłady

<!-- bad -->
<script>
  import { onMount } from 'svelte'
  onMount(() => window.addEventListener('keydown', onKey))
</script>
<!-- good -->
<svelte:window onkeydown={onKey} />

Źródła

Fakty

Identyfikator
svelte/window-events
Waga
drobna
Sprawdzanie
statyczne sprawdzane w kodzie źródłowym przez audit
Dotyczy plików
svelte
Tylko w projektach z
svelte sveltekit
Uczy jej skill
fe-svelte Svelte components
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain svelte/window-events