-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.gd
52 lines (41 loc) · 1.22 KB
/
store.gd
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
extends Node
var _state = {}
var _reducers = {}
signal state_changed(name, state)
func create(reducers, callbacks = null):
for reducer in reducers:
var name = reducer['name']
if not _state.has(name):
_state[name] = {}
if not _reducers.has(name):
_reducers[name] = funcref(reducer['instance'], name)
var initial_state = _reducers[name].call_func(
_state[name],
{'type': null}
)
_state[name] = initial_state
if callbacks != null:
for callback in callbacks:
subscribe(callback['instance'], callback['name'])
func subscribe(target, method):
connect('state_changed', target, method)
func unsubscribe(target, method):
disconnect('state_changed', target, method)
func dispatch(action):
for name in _reducers.keys():
var state = _state[name]
var next_state = _reducers[name].call_func(state, action)
if next_state == null:
_state.erase(name)
emit_signal('state_changed', name, null)
elif state != next_state:
_state[name] = next_state
emit_signal('state_changed', name, next_state)
func get_state():
return _state
func shallow_copy(dict):
return shallow_merge(dict, {})
func shallow_merge(src_dict, dest_dict):
for i in src_dict.keys():
dest_dict[i] = src_dict[i]
return dest_dict