1 |
|
2 |
|
3 |
|
4 | class DefaultStore {
|
5 | static VERSION = require('../package.json').version
|
6 |
|
7 | constructor () {
|
8 | this.state = {}
|
9 | this.callbacks = []
|
10 | }
|
11 |
|
12 | getState () {
|
13 | return this.state
|
14 | }
|
15 |
|
16 | setState (patch) {
|
17 | const prevState = Object.assign({}, this.state)
|
18 | const nextState = Object.assign({}, this.state, patch)
|
19 |
|
20 | this.state = nextState
|
21 | this._publish(prevState, nextState, patch)
|
22 | }
|
23 |
|
24 | subscribe (listener) {
|
25 | this.callbacks.push(listener)
|
26 | return () => {
|
27 |
|
28 | this.callbacks.splice(
|
29 | this.callbacks.indexOf(listener),
|
30 | 1
|
31 | )
|
32 | }
|
33 | }
|
34 |
|
35 | _publish (...args) {
|
36 | this.callbacks.forEach((listener) => {
|
37 | listener(...args)
|
38 | })
|
39 | }
|
40 | }
|
41 |
|
42 | module.exports = function defaultStore () {
|
43 | return new DefaultStore()
|
44 | }
|