榆树 - 如何使用HTML事件?

时间:2017-03-09 19:14:16

标签: elm

Elm getting started guide似乎没有使用标准的Elm HTML事件,我不知道如何使用它们。例如,onBlur

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

这在编译器中失败,因为现在我在第3行返回类型Html (String -> Msg),但在第2行返回Html (Msg)

为什么这两个事件不兼容?有没有办法同时使用这两种方法?此外,文档还不足以让像我这样的人了解如何使用onBlur

1 个答案:

答案 0 :(得分:4)

onBlur的类型签名与onInput不同。

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

onBlur : msg -> Attribute msg

这意味着您Msg使用的onInput必须采用单个字符串参数。同样,Msg中使用的onBlur也无法获取参数。如果您将MsgAMsgB重新定义为以下内容,则会编译:

type Msg
    = MsgA String
    | MsgB

修改

如果您希望模糊处理程序能够接受目标值,您可以像这样滚动自己:

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

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