Skip to content

Instantly share code, notes, and snippets.

@davidbalbert
Created November 19, 2024 15:45
Show Gist options
  • Save davidbalbert/e479c79ba51151af97c890ed13263f4f to your computer and use it in GitHub Desktop.
Save davidbalbert/e479c79ba51151af97c890ed13263f4f to your computer and use it in GitHub Desktop.
Simple JavaScript observation
// Returns [get, set]. Changes to the value can be observed with onChange.
function watch(value) {
let val = value;
function get() {
return val;
}
get.handlers = [];
function set(newValue) {
const old = val;
val = newValue;
if (old !== newValue) {
for (let h of get.handlers) {
h(newValue);
}
}
}
return [get, set];
}
// Handler is called when the value backed by getter changes.
function onChange(getter, handler) {
getter.handlers.push(handler);
}
// Creates an array of watched values. Returns [getAll, append, remove]
//
// getAll() returns the array of values.
// append() returns [get, set]
// remove(i) removes the i-th value
function watchN() {
const observations = [];
function getAll() {
return observations.map(get => get());
}
function append(value) {
const [get, set] = watch(value);
observations.push(get);
return [get, set];
}
function remove(i) {
values.splice(i, 1);
}
return [getAll, append, remove];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment