Skip to content

Instantly share code, notes, and snippets.

@scragg0x
Created May 16, 2017 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scragg0x/35d80e3aff93a29f2521aeffa1962a19 to your computer and use it in GitHub Desktop.
Save scragg0x/35d80e3aff93a29f2521aeffa1962a19 to your computer and use it in GitHub Desktop.
const objectChangeHandler = {
get(target, property) {
globalState.touched.push(target.id);
return target[property];
},
set(target, property, value, receiver) {
target[property] = value;
const cbs = globalState.callbacks[target.id];
if (cbs) {
for (const cb of cbs) {
cb();
}
}
return true;
},
};
const globalState = {
refs: {},
count: 0,
callbacks: {},
touched: [],
};
const observe = function (obj) {
const id = `M${globalState.count}`;
globalState.refs[id] = obj;
globalState.count++;
const proxyObj = new Proxy(obj, objectChangeHandler);
proxyObj.id = id;
return proxyObj;
};
const trackMe = observe({
x: 0,
});
const autoRun = function (f) {
globalState.touched = [];
f.call();
const deps = globalState.touched;
if (!globalState.callbacks[deps[0]]) {
globalState.callbacks[deps[0]] = [];
}
globalState.callbacks[deps[0]].push(f);
};
autoRun(() => {
console.log('auto run value is', trackMe.x);
});
setInterval(() => {
trackMe.x = Math.random();
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment