Elm Guide - small edit suggestion

In the example mdgriffith has defined only a single Msg:

type Msg
    = Update Form

and the anonymous function for onChange sends the Update variant of Msg. The password field of the form for instance uses this:

onChange = \new -> Update { model | password = new }

In this case the model is a Form type and the current model is being copied to the new model with a change to the password field.
The actual update function is:

update msg model =
    case Debug.log "msg" msg of
        Update new ->
            new

which just returns the new model to re-render the view (or at least the parts that need to be re-rendered).
This is nice efficient code, but you could re-write it a little more explicitly by having a Msg type for each field, which might be more human readable for you.

type alias Form =
    { username : String
    , password : String
    , agreeTOS : Bool
    , comment : String
    , lunch : Lunch
    , spiciness : Float
    }


type Msg
    = UpdateName String
    , UpdatePassword String
    , UpdateAgreeTOS bool
    , UpdateComment String
    , UpdateLunch Lunch
    , UpdateSpiciness Float

...

update msg model =
    case msg of
        UpdateName new -> { model | username = new }
        UpdatePassword new -> { model | password = new }
        UpdateAgreeTOS new -> { model | agreeTOS = new }
        UpdateComment new -> { model | comment = new }
        UpdateLunch new -> { model | lunch = new }
        UpdateSpiciness new -> { model | spiciness = new }

Now anywhere you need onChange you just send the Msg variant that is appropriate to the field. For the password field, for example:

onChange = \textInput -> UpdatePassword textInput

The update function will take that Msg and apply it to the model and return the new model to the view. Hope this helps. If you want additional help, I would suggest starting a new thread as this is somewhat off topic for this thread.

1 Like