尝试阻止默认设置时,键入带有自定义keydown事件的错误

时间:2019-05-05 13:43:44

标签: events elm

我意识到我必须在某个地方缺少一个参数,或者我的一个参数不正确,但是在尝试了所有我能想到的东西之后,我不确定该怎么做。

handleKeyDown : msg -> Attribute (Int -> Msg)
handleKeyDown message =
    custom "keydown" (Json.succeed { message = KeyPressed, stopPropagation = True, preventDefault = True })

view : Model -> Html Msg
view model =
    div []
        [ input
            [ handleKeyDown ]
            [ text "" ]
        ]

错误

The 1st argument to `input` is not what I expect:

104|         [ input
105|>            [ handleKeyDown ]
106|             [ text "" ]

This argument is a list of type:

    List #(msg -> Attribute (Int -> Msg))#

But `input` needs the 1st argument to be:

    List #(Attribute msg)#

1 个答案:

答案 0 :(得分:5)

这里有几个问题:

  1. <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <table id="trainings-table"> <thead> <tr> <th data-name="name">description</th> <th data-name="status">Status</th> <th data-name="date">date</th> <th date-name="duration">days</th> </tr> </thead> <tbody> <!-- Expected behaviour: This row below should be hidden after initialization --> <tr> <td>Training 1</td> <td>Completed</td> <td>28.04.2019</td> <td>1 day</td> </tr> <!-- Expected behaviour: Only show row below after initialization --> <tr> <td>Training 2</td> <td>Planned</td> <td>05.05.2019</td> <td>2 days</td> </tr> </tbody> </table>需要一个handleKeyDown参数,您不会使用它,也不会传递它。因此,类型为message,而不是预期的msg -> Attribute ...

  2. Attribute ...似乎具有类型KeyPressed的有效负载。因此,返回值为Int而不是Attribute (Int -> Msg)

假设您要使用Attribute Msg参数并从事件中获取message,这应该可以工作:

keyCode

在这里,handleKeyDown : (Int -> Msg) -> Html.Attribute Msg handleKeyDown tag = let options message = { message = message , stopPropagation = True , preventDefault = True } decoder = Json.field "keyCode" Json.int |> Json.map tag |> Json.map options in Html.Events.custom "keydown" decoder view : Model -> Html Msg view model = div [] [ input [ handleKeyDown KeyPressed ] [ text "" ] ] 期望带有有效负载handleKeyDown的标签/消息。内部事件解码器检索Int,将其包装在您传入的标签中,然后使用keyCode将其包装在options对象中。

但是请注意,preventDefault = True已过时,您可能想使用keyCodecode,它们都是字符串。