榆树:有条件的preventDefault(含contentEditable)

Sim*_*n H 5 elm

我正在尝试制作enter用于更新模型的内容可编辑标记.

我的代码如下,这是一个你可以在Ellie上玩的版本.

单击"模糊"属性可以在单击时使用并更新模型.但我希望在enter按下时获得相同的"更新"功能.

view : Model -> Html Msg
view model =
    let
        attrs =
            [ contenteditable True
              --, on "blur" (Json.map UpdateTitle targetTextContent)
            , onInput2 UpdateTitle
            , onEnter EnterPressed
            , id "title"
            , class "title"
            ]
    in
        div []
            [ h1 attrs [ text model.existing ]
            , text "Click above to start editing. Blur to save the value. The aim is to capture an <enter> and interpret that as a blur, i.e. to save the value and blur the field"
            , p [] [ text <| "(" ++ model.existing ++ ")" ]
            ]


targetTextContent : Json.Decoder String
targetTextContent =
    Json.at [ "target", "textContent" ] Json.string


onInput2 : (String -> msg) -> Attribute msg
onInput2 msgCreator =
    on "input" (Json.map msgCreator targetTextContent)


onEnter : (Bool -> msg) -> Attribute msg
onEnter enterMsg =
    onWithOptions "keydown"
        { stopPropagation = False
        , preventDefault = False
        }
        (keyCode
            |> Json.andThen
                (\ch ->
                    let
                        _ =
                            Debug.log "on Enter" ch
                    in
                        Json.succeed (enterMsg <| ch == 13)
                )
        )
Run Code Online (Sandbox Code Playgroud)

这段代码似乎正在更新模型,但DOM却搞砸了.例如,如果我enter在"爆炸"之后进入,我会看到这一点

在此输入图像描述

我尝试切换到Html.Keyed并使用"keydown",但它没有任何区别或只是创建了不同的问题.

Sim*_*n H 8

解决了!关键点是使用Json.Decode.fail的过滤器函数,因此只能使用<enter>preventDefault.请参阅https://github.com/elm-lang/virtual-dom/issues/18#issuecomment-273403774.

view : Model -> Html Msg
view model =
    let
        attrs =
            [ contenteditable True
            , on "blur" (Json.map UpdateTitle targetTextContent)
            , onEnter EnterPressed
            , id "title"
            , class "title"
            ]
    in
        div []
            [ h1 attrs [ text model.existing ]
            , text "Click above to start editing. Blur to save the value. The aim is to capture an <enter> and interpret that as a blur, i.e. to save the value and blur the field"
            , p [] [ text <| "(" ++ model.existing ++ ")" ]
            ]


targetTextContent : Json.Decoder String
targetTextContent =
    Json.at [ "target", "textContent" ] Json.string


onEnter : msg -> Attribute msg
onEnter msg =
    let
        options =
            { defaultOptions | preventDefault = True }

        filterKey code =
            if code == 13 then
                Json.succeed msg
            else
                Json.fail "ignored input"

        decoder =
            Html.Events.keyCode
                |> Json.andThen filterKey
    in
        onWithOptions "keydown" options decoder
Run Code Online (Sandbox Code Playgroud)