JavaScript

js/listener-cleanup

Listeners, timers and observers a view starts are removed when it goes away; one AbortController signal can end them all.

umiarkowanaręcznefe-javascript

Dlaczego

In a single-page app, a view that adds a resize listener, a setInterval or an IntersectionObserver and never removes it keeps running after navigation: memory grows, handlers fire twice after the view comes back, and they act on elements that no longer exist.

Poprawka

Create one AbortController per view or component, pass { signal } to every addEventListener and to fetch, and call abort() on teardown (the effect cleanup, onUnmounted, disconnectedCallback, DestroyRef.onDestroy). Clear timers with clearInterval and call disconnect() on observers in the same place.

Przykłady

// bad
connectedCallback() { window.addEventListener('resize', this.layout) }
// good
connectedCallback() {
  this.controller = new AbortController()
  window.addEventListener('resize', this.layout, { signal: this.controller.signal })
}
disconnectedCallback() { this.controller.abort() }

Źródła

Fakty

Identyfikator
js/listener-cleanup
Waga
umiarkowana
Sprawdzanie
ręczne ocenia człowiek; raport podaje to jako listę kontrolną
Dotyczy plików
jsx vue svelte astro html
Uczy jej skill
fe-javascript JavaScript in the browser
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain js/listener-cleanup