Skip to content

Instantly share code, notes, and snippets.

@AWaselnuk
Created July 8, 2016 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AWaselnuk/d0c9a01931c6e8e8a84d8743b6739df2 to your computer and use it in GitHub Desktop.
Save AWaselnuk/d0c9a01931c6e8e8a84d8743b6739df2 to your computer and use it in GitHub Desktop.
I don't understand custom event handlers and decoders in Elm
type alias Model =
{ level : Int
, name : String
}
type Msg
= ModifyLevel Int
| ModifyName String
levelOptionsView : Model -> Html Msg
levelOptionsView model =
let
levelDecoder =
Json.at ["target", "value"] Json.int
levelOption level isSelected =
option
[ value level
, selected isSelected
]
[ text level ]
levelOptions =
List.map
(\level -> levelOption (toString level) (level == model.level))
StatTables.levelList
in
select
[ name "character-level"
, on "change" (Json.map ModifyLevel levelDecoder)
]
levelOptions
@jvoigtlaender
Copy link

jvoigtlaender commented Jul 8, 2016

Try Json.string instead of Json.int here (in levelDecoder), and then convert from String to Int later?

@pdamoc
Copy link

pdamoc commented Jul 8, 2016

You can also use Html.Events.targetValue and convert its value into an int.

levelDecoder =
    Json.map ((Result.withDefault -1) << String.toInt)  Html.Events.targetValue

@artisonian
Copy link

artisonian commented Jul 8, 2016

Since event.target.value is a string in HTML, you'll have to parse the value as a string and convert it later. See my fork for an example (you can copy/paste it into elm-lang.org/try).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment