Created
July 8, 2016 12:44
-
-
Save AWaselnuk/d0c9a01931c6e8e8a84d8743b6739df2 to your computer and use it in GitHub Desktop.
I don't understand custom event handlers and decoders in Elm
This file contains 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
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 |
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
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
Try
Json.string
instead ofJson.int
here (inlevelDecoder
), and then convert fromString
toInt
later?