Working with hand-written JavaScript¶
Most of a component compiles from Python. Some things cannot: code needing loops, DOM ranges, a third-party widget or browser APIs outside the dialect. That code lives in a script of your own, loaded after the island, and meets the component through its signals.
window.__siting is the supported way in:
| Call | Does |
|---|---|
S.get(name) |
read a signal |
S.set(name, value) |
write a Local signal; what reads it updates |
S.effect(fn) |
run fn once the page's binders have, and again after any signal it read has changed. If it returns a function, that runs before the next run. Returns a function that stops it |
S.subscribe(name, fn) |
call fn(value) now and on every change |
S.afterSwap(fn) |
call fn(region) after a command has re-rendered the region, once its binders are live |
S.effect is what to reach for first. It follows what it reads, and runs once however many of those changed. It also runs after the binders, so the DOM it finds is up to date.
Two things to know:
S.subscribefires at once with the current value, before binders that subscribe later, and once per change. Read anything that value would overwrite, such aslocation.hash, before you subscribe.- Commands replace the region, so look elements up each time, or use
S.afterSwap. Elements in the<header>stay in place.
const S = window.__siting;
const widget = createWidget(document.querySelector("#chart"), {
onPick: (id) => S.set("selected_id", id), // from the widget to the signals
});
S.effect(() => widget.highlight(S.get("selected_id"))); // and back
<script defer src="{{ situ_runtime_url }}"></script>
<script defer src="{{ island_url }}"></script>
<script type="module" src="/static/widget.js"></script>
Anything else on window.__siting is internal, and may change.