javascript / expert
Snippet
Bridging Declarative UI and Imperative Web APIs via Actions
Svelte actions allow for surgical integration of imperative browser APIs like IntersectionObserver into the declarative component lifecycle. This pattern ensures that listeners are properly cleaned up when the element is unmounted, preventing memory leaks and keeping logic outside of the main script tag.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export function intersection(node, { threshold = 0, once = false }) {const observer = new IntersectionObserver((entries) => {entries.forEach(entry => {node.dispatchEvent(new CustomEvent('intersect', { detail: entry }));if (once && entry.isIntersecting) observer.unobserve(node);});}, { threshold });observer.observe(node);return {destroy() {observer.disconnect();}};}
svelte
Breakdown
1
node.dispatchEvent(new CustomEvent(...))
Communicates back to the Svelte component using native DOM events for a clean API.
2
destroy() { observer.disconnect(); }
Crucial lifecycle hook that runs when the element leaves the DOM, cleaning up the observer.