-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
68 lines (55 loc) · 1.35 KB
/
main.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
59
60
61
62
63
64
65
66
67
68
export const createDebouncer = (ms = 16) => {
let cancelDebounce = Function.prototype;
return (callback) => {
if (cancelDebounce !== Function.prototype) {
return cancelDebounce;
}
const timeout = setTimeout(() => {
cancelDebounce = Function.prototype;
callback();
}, ms);
cancelDebounce = () => {
clearTimeout(timeout);
};
return cancelDebounce;
}
}
export default class State {
constructor(
state = {},
onStateChange = Function.prototype,
debouncer = createDebouncer()
) {
this.initialState = state;
this.state = Object.assign({}, state);
this.onStateChange = onStateChange;
this.cancelDebounce = Function.prototype;
this.debounce = debouncer;
}
get() {
return this.state;
}
update(functionOrStateObject) {
let newState = {};
if (typeof functionOrStateObject === 'function') {
newState = functionOrStateObject(this.state);
} else {
newState = functionOrStateObject;
}
this.state = Object.assign({}, this.state, newState);
this.emit();
}
emit() {
this.cancelDebounce = this.debounce(() => {
this.onStateChange(this.state);
});
}
reset(state = {}) {
this.state = Object.assign({}, this.initialState, state);
this.emit();
}
destroy() {
this.cancelDebounce();
this.state = null;
}
}