function observable(initialState) {
const listeners = new Set();
const state = new Proxy(initialState, {
set(target, key, value) {
target[key] = value;
listeners.forEach((fn) => fn(key, value, target));
return true;
},
});
return {
state,
subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
},
};
}
// Usage
const { state, subscribe } = observable({ count: 0, name: 'Alice' });
subscribe((key, val) => console.log(`${key} changed to`, val));
state.count++; // count changed to 1
state.name = 'Bob'; // name changed to Bob
Create a free account and build your private vault. Share publicly whenever you want.