-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
58 lines (48 loc) · 1.27 KB
/
client.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
/**
* Created by cesar on 9/11/16.
*/
import {Tracker} from 'meteor/tracker'
const PREFIX = '___persistent_reactive_var___'
const set = function (key, val) {
localStorage.setItem(PREFIX + key, JSON.stringify(val));
}
const get = function (key) {
let val = localStorage.getItem(PREFIX + key)
if (val) val = JSON.parse(val)
return val
}
export class PersistentReactiveVar {
constructor(id, initialValue, expires) {
this.id = id
this.dep = new Tracker.Dependency;
this.setDefault(initialValue, expires)
window.addEventListener('storage', (ev) => {
if (ev.key === (PREFIX + id)) this.dep.changed()
})
}
set(val, expires) {
this.val = val
let options = {}
if (!isNaN(expires)) {
options = {expires}
if (expires > 0) {
Meteor.setTimeout(() => {
this.dep.changed()
}, expires + 100)
} else {
return
}
}
set(this.id, val);
this.dep.changed()
}
get() {
this.dep.depend()
return get(this.id);
}
setDefault(val, expires) {
if (get(this.id) === null) {
return this.set(val, expires)
}
}
}