Skip to content

Instantly share code, notes, and snippets.

@AGoblinKing
Created July 8, 2020 01:42
Show Gist options
  • Save AGoblinKing/45ef1199bf0a504b305fce66370ecdc5 to your computer and use it in GitHub Desktop.
Save AGoblinKing/45ef1199bf0a504b305fce66370ecdc5 to your computer and use it in GitHub Desktop.
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));
}
}
}
@AGoblinKing
Copy link
Author

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment