javascript / expert
Snippet
Explicit Resource Management via Symbol.asyncDispose inside Custom Svelte Actions
Integrates JavaScript's Explicit Resource Management (Symbol.asyncDispose) into Svelte node action lifecycle contracts. When the attached DOM node is unmounted, the action's destroy method asynchronously cleans up external connections like WebSockets or Web Workers cleanly.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function asyncDisposableAction(node, asyncResourceFactory) {let resource;(async () => {resource = await asyncResourceFactory(node);})();return {async destroy() {if (resource && typeof resource[Symbol.asyncDispose] === 'function') {await resource[Symbol.asyncDispose]();} else if (resource?.close) {await resource.close();}}};}
svelte
Breakdown
1
export function asyncDisposableAction(node, asyncResourceFactory) {
Declares a Svelte custom action taking a target DOM node and an async factory.
2
resource = await asyncResourceFactory(node);
Asynchronously initializes the targeted resource bound to the DOM node.
3
async destroy() {
Svelte lifecycle callback executed automatically when the node is detached from DOM.
4
if (resource && typeof resource[Symbol.asyncDispose] === 'function') {
Checks if the resource implements the standard ES async disposer interface.
5
await resource[Symbol.asyncDispose]();
Executes the asynchronous cleanup mechanism guaranteed by the disposer interface.