Skip to content

Instantly share code, notes, and snippets.

@YannDoy
Created January 4, 2019 15:59
Show Gist options
  • Save YannDoy/51b678c8aa40384aa3aa9da3d1a36ca7 to your computer and use it in GitHub Desktop.
Save YannDoy/51b678c8aa40384aa3aa9da3d1a36ca7 to your computer and use it in GitHub Desktop.
const rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || (fn => setTimeout(fn, 16));
function autorun(fn) {
const derivation = new Derivation(fn);
derivation.register();
return derivation;
}
function schedule(derivation) {
if (!!schedule.queue) return schedule.queue.add(derivation);
schedule.queue = new Set([ derivation ]);
rAF(() => {
schedule.queue.forEach(derivation => derivation.evaluate());
schedule.queue = null;
});
}
class Derivation {
constructor(fn) {
this.dependency = new Set();
this.evaluate = fn;
}
start() { this.dependency.forEach(track => track.derivations.add(this)); }
stop() { this.dependency.forEach(track => track.derivations.delete(this)); }
register() {
Derivation.current = this;
this.evaluate();
Derivation.current = null;
}
}
class Track {
constructor() {
this.derivations = new Set();
}
depend() {
const cur = Derivation.current
if (cur) {
cur.dependency.add(this);
this.derivations.add(cur);
}
}
update(changed = true) {
if (!changed) return;
this.derivations.forEach(schedule);
}
}
function property(obj, key, value) {
const track = new Track();
Object.defineProperty(obj, key, {
enumarable: true,
get() { return track.depend(), value; },
set(v) { track.update(v !== value, value = v); }
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment