Created
May 16, 2017 01:22
-
-
Save scragg0x/35d80e3aff93a29f2521aeffa1962a19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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