Public
Edited
Jan 2, 2024
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
// An implementation of the observer pattern
class Observable {
constructor(initialValue) {
this._value = initialValue;
this.observers = [];
}

read() {
return this._value;
}

write(newValue) {
if (newValue !== this._value) {
this._value = newValue;
this.notifyObservers();
}
}

// Method to add an observer
subscribe(observer) {
this.observers.push(observer);
}

// Method to notify all observers about the value change
notifyObservers() {
this.observers.forEach(observer => observer(this._value));
}
}
Insert cell
Insert cell
Insert cell
name = new Observable("Josh")
Insert cell
function component(state) {
console.log("Hello " + state)
}
Insert cell
name.subscribe(component)
Insert cell
// When you click this button, it will call name.read()
// We can use `read` to inspect the value of the Observable, but this isn't necessary for correct execution
viewof nameValue = Inputs.button("Read name", { value: null, reduce: () => name.read() })
Insert cell
nameValue
Insert cell
// When you submit a name in this field, it will be written to the `name` Observable.
viewof updatedName = Inputs.text({placeholder: "Enter your name", submit: true, autocomplete: false})
Insert cell
name.write(updatedName)
Insert cell
logTable(10)
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more