gpt4 book ai didi

Elm:有条件的 PreventDefault (内容可编辑)

转载 作者:行者123 更新时间:2023-12-03 04:53:34 25 4
gpt4 key购买 nike

我正在尝试制作一个内容可编辑标签,使用 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)
)
)

这段代码似乎可以正常更新模型,但 DOM 变得困惑。例如,如果我在“blast”后输入 enter,我会看到此内容

enter image description here

我尝试切换到 Html.Keyed 并使用“keydown”,但它没有任何区别或只是产生了不同的问题。

最佳答案

解决了!关键点是使用 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

关于Elm:有条件的 PreventDefault (内容可编辑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42390708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com