如何将键盘按键与操作关联

10

我已经开始掌握Elm,但在处理信号和键盘按键时仍然感到困惑。下面的代码是start-app包的示例。我希望当我按下空格键时,计数器会自动增加。如何在下面的示例中实现此功能?

import Html exposing (div, button, text)
import Html.Events exposing (onClick)
import StartApp.Simple as StartApp


main =
  StartApp.start { model = model, view = view, update = update }


model = 0


view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]


type Action = Increment | Decrement


update action model =
  case action of
    Increment -> model + 1
    Decrement -> model - 1 
1个回答

9
你需要使用常规 StartApp 而不是 StartApp.Simple,因为它提供了使用 Effects 和 Tasks 的方式。 Action 需要一个 NoOp 构造函数,以便在按键不是空格键时保持视图不变。
然后,你需要一个将 Keyboard.presses 值映射到 Action 的函数。以下是更新后的代码:
import Html exposing (div, button, text)
import Html.Events exposing (onClick)
import StartApp
import Effects exposing (Never)
import Task 
import Keyboard
import Char

app =
  StartApp.start
    { init = init
    , view = view
    , update = update
    , inputs = [ Signal.map spaceToInc Keyboard.presses ]
    }

main =
  app.html

type alias Model = Int

init =
  (0, Effects.none)

view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]

type Action
  = Increment
  | Decrement
  | NoOp

update action model =
  case action of
    NoOp -> (model, Effects.none)
    Increment -> (model + 1, Effects.none)
    Decrement -> (model - 1, Effects.none)

spaceToInc : Int -> Action
spaceToInc keyCode =
  case (Char.fromCode keyCode) of
    ' ' -> Increment
    _ -> NoOp

port tasks : Signal (Task.Task Never ())
port tasks =
  app.tasks

我有一个额外的问题。如果我想在同时按下两个按钮时进行递增,我该怎么做?我不能再使用Keyboard.presses,因为你无法检查它们是否同时被按下。 - Stanko
请查看Keyboard.keysDown。该信号会给你一个Set,其中包含当前按下的所有键。如果您试图确定按键而不是持续按下的键,则可能会遇到问题,但由于当其中一个键被释放时,您将获得新的信号,因此这可能是您想要的。 - Chad Gilbert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接