Using using for scoped cleanup
Problem
You set up drag-and-drop inside a function or block scope and want the cleanup to happen automatically when the block exits — without a try/finally or manual dispose() call.
Solution
Both primitives implement [Symbol.dispose], so they work with the using keyword in any block scope, including try blocks and async functions:
ts
import { createDropZone, createSortable } from '@vielzeug/dragit';
async function setupPage() {
using zone = createDropZone({
element: document.getElementById('dropzone')!,
onDrop: handleFiles,
});
using sortable = createSortable({
element: document.getElementById('list')!,
onReorder: saveOrder,
});
await pageReady();
// Both zone and sortable are still active here
// They are destroyed automatically when setupPage() returns or throws
}Pitfalls
usingrequires TypeScript 5.2+ and atsconfig.jsontargetofes2022or later. Without this,[Symbol.dispose]isundefinedat runtime.usingcalls[Symbol.dispose]on scope exit, not onreturn. If you return the value before the block exits, cleanup is still deferred until the scope ends.await usingrequires[Symbol.asyncDispose]. The synchronoususingkeyword calls[Symbol.dispose]synchronously — avoid it if cleanup involves async operations that must complete before proceeding.