Created
July 8, 2020 01:42
-
-
Save AGoblinKing/45ef1199bf0a504b305fce66370ecdc5 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 class Writable { | |
constructor(value) { | |
this.value = value; | |
this.callbacks = new Set(); | |
} | |
subscribe(callback) { | |
this.callbacks.add(callback); | |
callback(this.value); | |
return () => this.callbacks.delete(callback); | |
} | |
set(value) { | |
this.value = value; | |
for (let callback of this.callbacks) { | |
callback(this.value); | |
} | |
} | |
get() { | |
return this.value; | |
} | |
} | |
export class Persistable extends Writable { | |
constructor(table, value) { | |
super(value); | |
this.table = table; | |
const v = localStorage.getItem(table); | |
if (v === null) return; | |
try { | |
if (this.value instanceof Set) { | |
this.value = new Set(JSON.parse(v)); | |
} else { | |
Object.assign(this.value, JSON.parse(v)); | |
} | |
} catch (ex) {} | |
this.set(value); | |
} | |
set(value) { | |
super.set(value); | |
// update localStorage | |
if (this.value instanceof Set) { | |
localStorage.setItem(this.table, JSON.stringify([...value])); | |
} else { | |
localStorage.setItem(this.table, JSON.stringify(value)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MIT License