@benev/slate
Version:
frontend web stuff
48 lines • 1.13 kB
JavaScript
import { deep } from "./deep/deep.js";
export function ref(x, options = { dedupe: false }) {
return new Ref(x, options);
}
/**
* a wrapper for a value.
* subscribe to changes with the `on` method.
*/
export class Ref {
options;
#value;
#listeners = new Set();
constructor(x, options = { dedupe: false }) {
this.options = options;
this.#value = x;
}
on(fn, initiate = false) {
this.#listeners.add(fn);
if (initiate)
fn(this.#value);
return () => this.#listeners.delete(fn);
}
publish() {
const x = this.#value;
for (const fn of this.#listeners)
fn(x);
}
get value() {
return this.#value;
}
set value(x) {
if (this.options.dedupe) {
const changed = !deep.equal(this.#value, x);
if (changed) {
this.#value = x;
this.publish();
}
}
else {
this.#value = x;
this.publish();
}
}
dispose() {
this.#listeners.clear();
}
}
//# sourceMappingURL=ref.js.map