Created
February 8, 2020 22:05
-
-
Save VictorBezak/f64bd8bdcd58e596a47bf656d2e43b69 to your computer and use it in GitHub Desktop.
Another nested-record update example. This time with an additional helper function that handles a second update Msg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
import Html exposing (Html, div, section, button, text) | |
import Html.Attributes exposing (style) | |
import Html.Events exposing (onClick) | |
import Browser exposing (sandbox) | |
-- Type Schemas | |
type alias NestedRecord = | |
{ shoutout : String, grammyCount : Int } | |
type alias Model = | |
{ djkhaled : NestedRecord } | |
-- Model Initialization | |
init : Model | |
init = | |
{ djkhaled = { shoutout = "WE THE BEST", grammyCount = 0 } } | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ section [ style "font-size" "2em" ] [ text model.djkhaled.shoutout ] | |
, showGrammys model | |
, div [ style "display" "flex" ] | |
[ button [ onClick StartFromTheBottom ] [ text "start from the bottom" ] | |
, button [ onClick GrammyTime, style "margin-left" "12px" ] [ text "GET GRAMMY" ] | |
] | |
] | |
-- UPDATE | |
type Msg | |
= GrammyTime | |
| StartFromTheBottom | |
update : Msg -> Model -> Model | |
update msg model = | |
case msg of | |
GrammyTime -> | |
model | |
|> winGrammy | |
StartFromTheBottom -> | |
model | |
|> startFromTheBottom | |
showGrammys : Model -> Html a | |
showGrammys model = | |
div [ style "margin" "12px 0 24px 48px"] [ text ("Grammy Count: " ++ String.fromInt model.djkhaled.grammyCount) ] | |
-- Helper functions to update our nested record | |
updateModel : (NestedRecord -> NestedRecord) -> Model -> Model | |
updateModel updateFunction model = | |
{ model | djkhaled = updateFunction model.djkhaled } | |
getAnothaOne : NestedRecord -> NestedRecord | |
getAnothaOne nestedRecord = | |
{ nestedRecord | |
| shoutout = "ANOTHA ONE" | |
, grammyCount = nestedRecord.grammyCount + 1 | |
} | |
loseItAll : NestedRecord -> NestedRecord | |
loseItAll nestedRecord = | |
{ nestedRecord | |
| shoutout = "WE STILL THE BEST" | |
, grammyCount = 0 | |
} | |
winGrammy : Model -> Model | |
winGrammy = | |
updateModel <| getAnothaOne | |
startFromTheBottom : Model -> Model | |
startFromTheBottom = | |
updateModel <| loseItAll | |
main : Program () Model Msg | |
main = | |
Browser.sandbox | |
{ init = init | |
, view = view | |
, update = update | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment