Using elm higher order functions for keyboard events

对着背影说爱祢 提交于 2019-12-05 03:34:41

You are adding two onkeydown attributes to the input element, and only one of them can win. The second in the list overwrites the first. Were it to use addEventListener behind the scenes, this would not be the case, but for now we can solve it with a slightly different approach.

You could write a onKeysDown function that accepts a list of possible key codes and the message they should invoke like this:

onKeysDown : List (Int, Msg) -> Attribute Msg
onKeysDown keys =
  let
    captureKey code =
      List.filterMap (\(k, m) -> if k == code then Just m else Nothing) keys
        |> List.head
        |> Maybe.withDefault NoOp
  in
    on "keydown" (Json.map captureKey keyCode)

You could then write shorthand functions for handling specific keys like this:

enter msg = (13, msg)
esc msg = (27, msg)

And now you can use it in your view like this:

input
    [ ...
    , onKeysDown
      [ enter <| SwitchEditTodo item.uid False
      , esc <| UndoEditTodo item.uid
      ]
    ]

This works because it generates a single keydown event handler attribute. And while you substitute a predefined tuple for a higher order function, it still gives you just as readable code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!