我希望有人能在信号和效果方面帮助我。
我正在研究 Signals/Effects 并且一直在研究 the-elm-architecture,特别是example 8。
在这个例子中(据我所知),如果你点击形状:
- 信号消息与操作一起发送到地址
- 该
SPIN
操作在更新时触发 - 如果他的形状当前没有动画,也会调用 Tick。
我正在尝试复制完全相同的流程(使用类似的代码),但我不想单击按钮并使用 HTML 包,而是只想使用空格键发送信号。
在我的代码中,空格键向操作发送信号Punch
。就像示例 8 一样,我还想在我的模型中调用Tick
并更新。debounceState
你会在我的评论中看到我可以达到我的Punch
行动,但我似乎从来没有达到过Tick
。
我看过这个问题,但是因为我使用的是键盘信号而不是榆树 StartApp,所以我认为它不适用。
如果有人可以在我的示例中解释为什么我无法联系到Tick
,我将非常感激。
module Main (..) where
import Graphics.Element exposing (..)
import Time exposing (Time, second)
import Effects exposing (Effects)
import Keyboard
type alias DebounceState =
Maybe
{ prevClockTime : Time
, elapsedTime : Time
}
type alias Model =
{ punching : Bool
, count : Int
, randomString: String
, debounceState : DebounceState
}
duration = second
-- MODEL
initialModel : ( Model, Effects Action )
initialModel =
( { punching = False
, count = 0
, randomString = ""
, debounceState = Nothing
}
, Effects.none
)
model : Signal ( Model, Effects Action )
model =
Signal.foldp update initialModel (punch Keyboard.space)
-- ACTIONS
type Action
= NoOp
| Punch Bool
| Tick Time
-- UPDATE
update : Action -> ( Model, Effects Action ) -> ( Model, Effects Action )
update action ( model, fx ) =
case action of
NoOp ->
( model, Effects.none )
Punch isPunching ->
case model.debounceState of
Nothing ->
( { model |
punching = isPunching
, count = model.count + 1 }, Effects.tick Tick )
Just _ ->
( { model |
punching = isPunching
, count = model.count + 2 }, Effects.none )
-- I don't seem to reach `Tick` at all
-- You'll notice that I try to apply a value to `randomString` in the
-- conditional to indicate where I end up
Tick clockTime ->
let
newElapsedTime =
case model.debounceState of
Nothing ->
0
Just {elapsedTime, prevClockTime} ->
elapsedTime + (clockTime - prevClockTime)
in
if newElapsedTime > duration then
( {model | randomString = "foo"} , Effects.none )
else
( {model | randomString = "bar"} , Effects.tick Tick )
-- SIGNAL
punch : Signal Bool -> Signal Action
punch input =
Signal.map Punch input
-- VIEW
view : ( Model, Effects Action ) -> Element
view model =
show model
main : Signal Element
main =
Signal.map view model
将其直接粘贴到Try Elm中。