switch with init
- Switches can be initialized to provide a starting value.
- This snippet uses the
b.savePageData() and
b.loadPageData() to save state between page
reloads as well.
html
<div data-r="initSwitches"></div>
<script type="text/html" data-template="toggleWrapper">
<div class="toggleWrapper">
<div>
__KEY_ATTR__ is:
<span
data-r="display"
data-key="__KEY__"
>__DISPLAY__</span>
</div>
__SWITCH__
</div>
</script>
javascript
export const b = { init: "addStyles initSwitches" };
let data;
export async function initSwitches(_, __, el) {
const defaults = { alfa: false, bravo: true, charlie: true, delta: false };
data = await b.loadPageData("state", defaults);
el.replaceChildren(
...Object.keys(data).map((key) => {
const subs = {
__PREPEND__: key,
__KEY__: key,
__SEND__: "toggle",
__STATE__: data[key],
__DISPLAY__: data[key] ? "on" : "off",
};
const switchEl = b.switch(subs);
subs["__SWITCH__"] = switchEl;
return b.render("toggleWrapper", subs);
}),
);
}
export async function toggle(_, sender, ___) {
sender.setAria("checked", !sender.ariaAsBool("checked"));
data[sender.prop("key")] = sender.ariaAsBool("checked");
await b.savePageData(data, "state");
b.send(sender.prop("key"), "display");
}
export function display(key, __, el) {
if (el.prop("key") === key) {
el.innerHTML = data[key] ? "on" : "off";
}
}