steel
steel

Reputation: 12520

Elm - How to use HTML events?

The Elm getting started guide doesn't seem to use the standard Elm HTML events and I'm not sure how to use them. For example, onBlur:

view model =
  div []
    [ div []
      input [ type_ "text", onInput MsgA ] []
    , input [ type_ "text", onBlur MsgB ] []
    ]

This fails in the compiler because now I am returning type Html (String -> Msg) on line 3 but Html (Msg) in line two.

Why are these two events incompatible? Is there any way to use both at the same time? Additionally, the docs don't make it clear enough for someone like me to understand how to use onBlur.

Upvotes: 2

Views: 1021

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

onBlur has a different type signature than onInput.

onInput : (String -> msg) -> Attribute msg

onBlur : msg -> Attribute msg

That means whatever Msg you use for onInput has to take a single string parameter. Likewise, the Msg used in onBlur cannot take a parameter. If you redefined MsgA and MsgB to the following, it would compile:

type Msg
    = MsgA String
    | MsgB

Edit

If you wanted your blur handler to be able to accept the target value, you can roll your own like this:

import Html.Events exposing (on, targetValue)
import Json.Decode as Json

onBlurWithTargetValue : (String -> msg) -> Attribute msg
onBlurWithTargetValue tagger =
    on "blur" (Json.map tagger targetValue)

Upvotes: 4

Related Questions