I'm getting the hang of Elm but I keep struggling with signals and keyboard presses. The code below is an example of the start-app package. I would like to have that when I press the spacebar that the counter is incremented. How is this done in the example below?
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
You'll need to use regular StartApp
rather than StartApp.Simple
because it provides the means to use Effects and Tasks.
The Action
needs a NoOp
constructor to allow our view to remain unchanged when a key press is not the spacebar.
Then you'll need a function which maps the Keyboard.presses
value to an Action
. Here's the updated code:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With