榆树检查是否按下了ctrl键

时间:2016-01-03 15:59:43

标签: elm

使用elm-html,如何在点击时检查是否按下了ctrl键?

“控制键是否”某些状态我需要在其他地方维护,也许使用键盘模块?如果是这样,那将如何适合elm-html?

我已经从一个众所周知的榆树示例中修改了以下代码:

import Keyboard
import Html exposing (..)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Signal exposing(Signal, Mailbox)


type alias Model =
  { count: Int
  , ctrl : Bool
}

initialModel : Model
initialModel = { count = 0, ctrl = False}

type Action = Increment | Decrement | NoOp

update : Action -> Model -> Model
update action model =
  case action of
    Increment ->
      { model | count = model.count + 1 }
    Decrement ->
      { model | count = model.count - 1 }
    NoOp ->
      model


view : Signal.Address Action -> Model -> Html
view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]


actions : Mailbox Action
actions =
  Signal.mailbox NoOp

model : Signal Model
model =
  Signal.foldp update initialModel actions.signal -- Keyboard.ctrl ?

main =
  Signal.map (view actions.address) model

如何更新模型的“ctrl”字段的值?

1 个答案:

答案 0 :(得分:2)

首先需要一个能够设置是否按下 CTRL 的值的动作:

type Action = Increment | Decrement | SetCtrl Bool | NoOp

更新功能中的case语句需要处理该新操作:

SetCtrl bool -> { model | ctrl = bool }

现在你需要一个可以将Keyboard.ctrl布尔值映射到任务的端口,该任务使用新的Action发送信号:

port ctrlToAction : Signal (Task.Task Effects.Never ())
port ctrlToAction =
  Signal.map (Signal.send actions.address << SetCtrl) Keyboard.ctrl