Public
Edited
Nov 2, 2021
Insert cell
# Reactivity with `Proxy`
Insert cell
{
let target = null;

class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach((sub) => sub());
}
}

let data = {
price: 20,
amount: 5
};

let deps = new Map();

Object.keys(data).forEach((key) => {
deps.set(key, new Dep());
});

let data_without_proxy = data;

data = new Proxy(data_without_proxy, {
get(obj, key) {
deps.get(key).depend();
return obj[key];
},
set(obj, key, newVal) {
obj[key] = newVal;
deps.get(key).notify();
return true;
}
});

function watcher(fn) {
target = fn;
target();
target = null;
}

let total;

watcher(() => {
total = data.price * data.amount;
});

const ret = [total];
data.price = 30;
ret.push(total);
return ret;
}
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