Skip to content

Instantly share code, notes, and snippets.

@DylanPiercey
Created December 7, 2023 18:11
Show Gist options
  • Save DylanPiercey/968f585ee6f72f21138038d75e02bb44 to your computer and use it in GitHub Desktop.
Save DylanPiercey/968f585ee6f72f21138038d75e02bb44 to your computer and use it in GitHub Desktop.
marko global state
const valuesById = new Map();
const listenersById = new Map();
export function withGlobalState(component, out, id, state = {}) {
if (typeof document === "undefined") {
if (Array.isArray(id)) {
for (const item of id) {
withGlobalState(component, out, item, state);
}
} else {
state[id] = out.global[id];
}
return state;
}
if (Array.isArray(id)) {
for (const item of id) {
withGlobalState(component, out, item, state);
}
} else {
if (valuesById.has(id)) {
state[id] = valuesById.get(id);
} else {
valuesById.set(id, state[id] = out.global[id]);
}
let listeners = listenersById.get(id);
if (listeners) {
listeners.push(component);
} else {
listeners = [component];
listenersById.set(id, listeners);
}
component.once("destroy", () => {
const last = listeners.pop();
if (component !== last) {
listeners[listeners.indexOf(component)] = last;
}
});
}
return state;
}
export function setGlobalState(id, value) {
if (typeof document === "undefined") {
throw new Error("Cannot set global state on the server, use $global instead");
}
const listeners = listenersById.get(id);
valuesById.set(id, value);
if (listeners) {
for (const listener of listeners) {
listener.setState(id, value);
}
}
}
@DylanPiercey
Copy link
Author

Dumb global value pubsub that falls back to Marko's out.global and automatically synchronizes values with component state.

https://markojs.com/playground/#NobwRAdghgtgpmAXGAlhAJnAHgOhlAJwGsB7MAGjAAcoAXACyTAHoBjEmKkiOCWgZ2ZpMufMTKV2fXrSYpOJArQAEIZQHcUDAOIAbEgCMougMq06cZQF9lAMwIdlAHTA5mAc31HdAWn7naOBcAbicIMNZdKH5+VTDlBOVuAGECOAsACjQqAFdaciS8gEo4iETy5QYUfhx-C2UAXg0tej1DYzNMqv4CkjyC4BcoFwKXAxcAXSLQssSrMPnwiB8fZQASEDrAnCgbDa24HANFgB5Pdt8qBwA3FEwCZgA+MCtycGh4JnPvPwDDgCt+BRqHRGMg2BwuDw+IJvsZfhYcIDgVJAnwmFJ-Mpr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