-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (95 loc) · 2.27 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* @module Store
* @package @fiad/toolbox
* @description A simple state management handler
*/
import EventsBus from '../events-bus'
import equal from '../utils/equal'
class Store {
/**
* The original store's state
* @private
* @type {object}
*/
#originalState = {}
/**
* The store's state
* @private
* @type {object}
*/
#state = {}
/**
* The inner instance of event bus
* @private
* @type {EventBus}
*/
#bus = new EventsBus()
/**
* @constructor
* @param {object} state The initial store's state
*/
constructor(state = {}) {
this.#originalState = state
this.#state = state
}
/**
* State getter
* @param {(string|null)} key The property key to be retrieved
*/
get(key) {
return key ? this.#state[key] : this.#state
}
/**
* State setter
* @param {...any} args
*/
set(...args) {
switch (typeof args[0]) {
case 'string':
if (!equal(this.get(args[0]), args[1])) {
this.#state[args[0]] = args[1]
this.#bus.dispatch(args[0], args[1])
}
break
case 'function':
this.set(args[0](this.#state))
break
default:
Object
.entries(args[0])
.forEach(([key, value]) => this.set(key, value))
break
}
}
/**
* Resets store to its original state
*/
reset() {
this.set(this.#originalState)
}
/**
* Adds a listener that observes changes on the given property
* @param {(string|string[])} key The property (or properties) to be observed
* @param {function} callback The handler to be called when a property update occurs
*/
observe(key, callback) {
if (Array.isArray(key)) {
key.forEach(k => this.#bus.subscribe(k, callback))
} else {
this.#bus.subscribe(key, callback)
}
}
/**
* Removes the listener that observes changes on the given property
* @param {(string|string[])} key The property (or properties) to be unobserved
* @param {function} callback The handler that no longer needs to be called when a property update occurs
*/
unobserve(key, callback) {
if (Array.isArray(key)) {
key.forEach(k => this.#bus.unsubscribe(k, callback))
} else {
this.#bus.unsubscribe(key, callback)
}
}
}
export default Store