-
Notifications
You must be signed in to change notification settings - Fork 0
/
storable.js
58 lines (46 loc) · 1.42 KB
/
storable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Author: Mats Sommervold - https://github.com/matssom/svelte-storable.git - MIT license
import { writable } from 'svelte/store';
class Store {
key
store
constructor(key, initialValue) {
if(typeof key === 'undefined') throw new Error('Storables require a key to interact with local storage')
this.key = key
this.store = this._exists() ? writable(this._getData()) : writable(initialValue)
this.set = this.set.bind(this);
this.update = this.update.bind(this);
this.subscribe = this.subscribe.bind(this);
this.detatch = this.detatch.bind(this);
}
_exists () { return !!localStorage.getItem(this.key) }
_getData() {
const DATA = localStorage.getItem(this.key)
return JSON.parse(DATA)
}
_setData(data) {
const DATA = JSON.stringify(data)
localStorage.setItem(this.key, DATA)
}
set(data) {
this._setData(data)
this.store.set(data)
}
update(callback) {
const update = (data) => {
const newData = callback(data)
this._setData(newData)
return newData
}
this.store.update(update);
}
subscribe(callback) {
return this.store.subscribe(callback)
}
detatch() {
localStorage.removeItem(this.key)
return true
}
}
export const storable = (key, initialValue) => {
return new Store(key, initialValue);
}