forked from hexops/vecty
/
store.go
85 lines (67 loc) · 1.81 KB
/
store.go
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
package store
import (
"github.com/gopherjs/vecty/example/todomvc/actions"
"github.com/gopherjs/vecty/example/todomvc/dispatcher"
"github.com/gopherjs/vecty/example/todomvc/store/model"
"github.com/gopherjs/vecty/example/todomvc/store/storeutil"
)
var (
// Items represents all of the TODO items in the store.
Items []*model.Item
// Filter represents the active viewing filter for items.
Filter = model.All
// Listeners is the listeners that will be invoked when the store changes.
Listeners = storeutil.NewListenerRegistry()
)
func init() {
dispatcher.Register(onAction)
}
// ActiveItemCount returns the current number of items that are not completed.
func ActiveItemCount() int {
return count(false)
}
// CompletedItemCount returns the current number of items that are completed.
func CompletedItemCount() int {
return count(true)
}
func count(completed bool) int {
count := 0
for _, item := range Items {
if item.Completed == completed {
count++
}
}
return count
}
func onAction(action interface{}) {
switch a := action.(type) {
case *actions.ReplaceItems:
Items = a.Items
case *actions.AddItem:
Items = append(Items, &model.Item{Title: a.Title, Completed: false})
case *actions.DestroyItem:
copy(Items[a.Index:], Items[a.Index+1:])
Items = Items[:len(Items)-1]
case *actions.SetTitle:
Items[a.Index].Title = a.Title
case *actions.SetCompleted:
Items[a.Index].Completed = a.Completed
case *actions.SetAllCompleted:
for _, item := range Items {
item.Completed = a.Completed
}
case *actions.ClearCompleted:
var activeItems []*model.Item
for _, item := range Items {
if !item.Completed {
activeItems = append(activeItems, item)
}
}
Items = activeItems
case *actions.SetFilter:
Filter = a.Filter
default:
return // don't fire listeners
}
Listeners.Fire()
}