-
-
Save mnpenner/1216bd96ba7d8430fa804781f9be0da9 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
export default class Store { | |
constructor() { | |
this.subscriptions = Object.create(null); | |
this.data = Object.create(null); | |
// this.counter = 0; | |
this._fireSubscriptions = debounce(context => { | |
for(let [k,v] of Object.entries(this.subscriptions)) { | |
let newValue = getValue(this.data, v[0]); | |
if(!Object.is(v[2],newValue)) { | |
v[1](newValue, v[2], context); | |
v[2] = newValue; | |
} | |
} | |
const elapsed = performance.now() - start; | |
}); | |
} | |
subscribe(path, callback) { | |
path = toPath(path); | |
let key = shortid(); | |
this.subscriptions[key] = [path,callback,getValue(this.data,path)]; | |
const unsub = () => { | |
delete this.subscriptions[key]; | |
}; | |
unsub.key = key; | |
return unsub; | |
} | |
get(path) { | |
return getValue(this.data, path); | |
} | |
unset(path) { | |
if(unset(this.data, path)) { | |
this._fireSubscriptions(); | |
} | |
} | |
set(path, value, context) { | |
path = toPath(path); | |
let oldValue = getValue(this.data, path); | |
if(typeof value === 'function') { | |
value = value(oldValue); | |
} | |
if(Object.is(oldValue, value)) return; | |
setValue(this.data, path, value); | |
this._fireSubscriptions(context); | |
} | |
toJSON() { | |
// TODO: strip undefined values? | |
return this.data; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment