-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.lua
76 lines (63 loc) · 1.71 KB
/
store.lua
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
function createStore()
return [[
return {
__hooks = {},
__state = {},
__events = {},
__computedProperties = {},
__actionHandler = nil,
__helpers = {
shallowCopy = function(original)
local copy = {}
for key, value in pairs(original) do
copy[key] = value
end
return copy
end,
},
onAction = function(self, callback)
self.__actionHandler = callback
end,
setComputedProperty = function(self, value, callback)
self.__computedProperties[value] = callback
end,
setHook = function(hookName, callback)
self.__hooks[hookName] = callback
end,
dispatch = function(self, name, payload)
if self.__hooks["beforeAction"] then
self.__hooks["beforeAction"](name, payload)
end
self.__actionHandler(name, payload)
if self.__hooks["afterAction"] then
self.__hooks["afterAction"](name, payload)
end
end,
getState = function(self)
return self.__helpers.shallowCopy(self.__state)
end,
setState = function(self, state)
for fieldName, fieldValue in pairs(state) do
self.__state[fieldName] = fieldValue
if self.__computedProperties[fieldName] then
self.__computedProperties[fieldName]()
self:emit("computed_update")
end
end
self:emit("update")
end,
setInitialState = function(self, initialState)
self.__state = initialState
self:emit("initial_state_set")
end,
on = function(self, eventName, callback)
self.__events[eventName] = callback
end,
emit = function(self, eventName)
if self.__events[eventName] then
self.__events[eventName]()
end
end,
}
]]
end