more efficient localstorage store

This commit is contained in:
Nolan Lawson 2018-01-12 22:05:57 -08:00
parent e71c30fcac
commit 6b1c047bcd
1 changed files with 22 additions and 5 deletions

View File

@ -1,21 +1,38 @@
import { Store } from 'svelte/store.js' import { Store } from 'svelte/store.js'
const key = 'ui-store' const key = 'ui-store'
const LS = process.browser && localStorage
class LocalStorageStore extends Store { class LocalStorageStore extends Store {
constructor(state) { constructor(state) {
super(state) super(state)
if (process.browser) { if (process.browser) {
let cached = localStorage.getItem(key) this.lastChanged = {}
if (cached) { let newState = {}
this.set(JSON.parse(cached)) for (let i = 0, len = LS.length; i < len; i++) {
let key = LS.key(i)
if (key.startsWith('store_')) {
let item = LS.getItem(key)
newState[key.substring(6)] = item === 'undefined' ? undefined : JSON.parse(item)
}
} }
this.set(newState)
this.onchange((state, changed) => {
Object.keys(changed).forEach(change => {
if (!this._computed[change]) { // TODO: better way to ignore computed values?
this.lastChanged[change] = true
}
})
})
} }
} }
save() { save() {
if (process.browser) { if (process.browser) {
localStorage.setItem(key, JSON.stringify(this._state)) Object.keys(this.lastChanged).forEach(key => {
LS.setItem(`store_${key}`, JSON.stringify(this.get(key)))
})
this.lastChanged = {}
} }
} }
} }