Window & Document
Attach window and document event listeners whose lifetime follows their position in the tree.
Some events don't belong to any element in your tree, they belong to the page. ImplementWindow and ImplementDocument attach event listeners to the global objects for as long as they are mounted (the counterpart of Svelte's <svelte:window>/<svelte:document>). They render nothing.
import { ImplementDocument, ImplementWindow } from "@implementjs/core";
ImplementWindow({ onResize: relayout, onHashchange: onRoute });
ImplementDocument({ onKeydown: handleShortcuts });
Lifetime follows tree position
Because listeners attach on mount and detach on unmount, placing one inside a branch scopes it to that branch. No manual addEventListener/removeEventListener bookkeeping:
If(menuOpen).Then(
MenuPanel(),
ImplementDocument({
onMousedown: (event) => {
if (!panel.get()?.contains(event.target as Node)) menuOpen.set(false);
},
onKeydown: (event) => {
if (event.key === "Escape") menuOpen.set(false);
},
}),
);
When the menu closes, the branch unmounts and both listeners detach.
Props
- Handlers use the same
on+ capitalized name convention as elements, typed againstWindowEventMap/DocumentEventMap.onResize,onScroll,onKeydown,onVisibilitychange,onPopstate, and so on. - Append
Captureto listen in the capture phase, likeonMousedownCaptureoronFocusinCapture. - A handler can be a
Readableof a function and the listener is swapped when it changes. event.targetis not narrowed to the global object. For a documentkeydownit is whatever element had focus, just like in the browser.
You now have every building block. The final part assembles them into a real application, starting with the router.