Skip to content

Instantly share code, notes, and snippets.

@idiotWu
Created May 18, 2017 09:08
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 idiotWu/8dcc1b51f166362bdbf3ec9246dffc06 to your computer and use it in GitHub Desktop.
Save idiotWu/8dcc1b51f166362bdbf3ec9246dffc06 to your computer and use it in GitHub Desktop.
A fake observable
let currentCaller = null;
class FakeObservable {
constructor() {
this._value = null;
this._callers = new Set();
}
set(val) {
this._value = val;
this._callers.forEach(cb => cb());
}
get() {
this._callers.add(currentCaller);
return this._value;
}
}
function autorun(callback) {
if (typeof callback !== 'function') return;
currentCaller = callback;
callback();
}
/********* TEST *********/
const obs = new FakeObservable();
autorun(() => {
console.log('value updated:', obs.get());
});
// log: null
obs.set(1); // log: 1
obs.set(2); // log: 2
obs.set(666); // log: 666
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment