forked from evancz/elm-architecture-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounterList.elm
71 lines (52 loc) · 1.56 KB
/
CounterList.elm
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
module CounterList where
import Counter
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
-- MODEL
type alias Model =
{ counters : List ( ID, Counter.Model )
, nextID : ID
}
type alias ID = Int
init : Model
init =
{ counters = []
, nextID = 0
}
-- UPDATE
type Action
= Insert
| Remove
| Modify ID Counter.Action
update : Action -> Model -> Model
update action model =
case action of
Insert ->
let newCounter = ( model.nextID, Counter.init 0 )
newCounters = model.counters ++ [ newCounter ]
in
{ model |
counters <- newCounters,
nextID <- model.nextID + 1
}
Remove ->
{ model | counters <- List.drop 1 model.counters }
Modify id counterAction ->
let updateCounter (counterID, counterModel) =
if counterID == id
then (counterID, Counter.update counterAction counterModel)
else (counterID, counterModel)
in
{ model | counters <- List.map updateCounter model.counters }
-- VIEW
view : Signal.Address Action -> Model -> Html
view address model =
let counters = List.map (viewCounter address) model.counters
remove = button [ onClick address Remove ] [ text "Remove" ]
insert = button [ onClick address Insert ] [ text "Add" ]
in
div [] ([remove, insert] ++ counters)
viewCounter : Signal.Address Action -> (ID, Counter.Model) -> Html
viewCounter address (id, model) =
Counter.view (Signal.forwardTo address (Modify id)) model