Created
May 18, 2017 09:08
-
-
Save idiotWu/8dcc1b51f166362bdbf3ec9246dffc06 to your computer and use it in GitHub Desktop.
A fake observable
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
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