我掌握了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
最佳答案
您需要使用常规的 StartApp
而不是StartApp.Simple
,因为它提供了使用效果和任务的方法。Action
需要一个NoOp
构造函数,以便当按键不是空格键时,我们的 View 保持不变。
然后,您将需要一个将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 - 如何将键盘按动链接到 Action ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34276034/