Skip to content

Instantly share code, notes, and snippets.

@pdamoc
Created August 30, 2016 07:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdamoc/4f6cfc7ff5f69aeb527c3fff52550fd2 to your computer and use it in GitHub Desktop.
Save pdamoc/4f6cfc7ff5f69aeb527c3fff52550fd2 to your computer and use it in GitHub Desktop.
CounterList Example without nesting.
module Main exposing (..)
import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (..)
main =
App.beginnerProgram
{ model = init
, update = update
, view = view
}
-- MODEL
type alias Model =
{ counters : List IndexedCounter
, uid : Int
}
type alias IndexedCounter =
{ id : Int
, model : Int
}
init : Model
init =
{ counters = []
, uid = 0
}
-- UPDATE
type Msg
= Insert
| Remove
| Modify Int Int
-- ID DELTA
update : Msg -> Model -> Model
update message ({ counters, uid } as model) =
case message of
Insert ->
{ model
| counters = counters ++ [ IndexedCounter uid 0 ]
, uid = uid + 1
}
Remove ->
{ model | counters = List.drop 1 counters }
Modify id delta ->
{ model | counters = List.map (updateHelp id delta) counters }
updateHelp : Int -> Int -> IndexedCounter -> IndexedCounter
updateHelp targetId delta { id, model } =
IndexedCounter id
(if targetId == id then
model + delta
else
model
)
-- VIEW
view : Model -> Html Msg
view model =
let
remove =
button [ onClick Remove ] [ text "Remove" ]
insert =
button [ onClick Insert ] [ text "Add" ]
counters =
List.map viewIndexedCounter model.counters
in
div [] ([ remove, insert ] ++ counters)
viewIndexedCounter : IndexedCounter -> Html Msg
viewIndexedCounter { id, model } =
counter (Modify id 1) (Modify id -1) model
-- COUNTER
counter : msg -> msg -> Int -> Html msg
counter inc dec val =
div []
[ button [ onClick dec ] [ text "-" ]
, div [ countStyle ] [ text (toString val) ]
, button [ onClick inc ] [ text "+" ]
]
countStyle : Attribute msg
countStyle =
style
[ ( "font-size", "20px" )
, ( "font-family", "monospace" )
, ( "display", "inline-block" )
, ( "width", "50px" )
, ( "text-align", "center" )
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment