我想知道为什么这不起作用。我试图去抖动,但不是视图中的用户事件。根据想法,这应该进入连续流,这将发生一次,但每隔几秒。这种架构的主要思想是可以从各个地方触发事件,但它只会发生一次。我做了一个简单的示例应用程序:
module Main exposing (main)
import Html exposing (Html)
import Html
import Process
import Task
import Debug
import Time
import Control exposing (Control)
import Control.Debounce as Debounce
main : Program Never Model Msg
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
type alias Model =
{ counter : Int
, state : Control.State Msg
}
init : ( Model, Cmd Msg )
init =
{ counter = 0, state = Control.initialState }
! [ delay (Time.second * 3) <| ContinuousDebouncing ]
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
type Msg
= Deb (Control Msg)
| ContinuousDebouncing
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Deb debMsg ->
Control.update (\s -> { model | state = s }) model.state debMsg
ContinuousDebouncing ->
let
x = Debug.log "ContinuousDebouncing"
_ = debounce ContinuousDebouncing
in
( { model | counter = model.counter + 1 }, Cmd.none )
debounce : Msg -> Msg
debounce =
let
x = Debug.log "debounce"
in
Debounce.trailing Deb (3 * Time.second)
delay : Time.Time -> msg -> Cmd msg
delay time msg =
Process.sleep time
|> Task.andThen (always <| Task.succeed msg)
|> Task.perform identity
view : Model -> Html Msg
view model =
Html.text (toString model.counter)
答案 0 :(得分:2)
在您的示例应用中,您只在ContinuousDebouncing
函数中触发了一次init
msg,因此正如预期的那样,计数器仅递增一次。您可能希望在更新功能中再次触发ContinuousDebouncing
。
我认为这可以实现你所追求的目标:
module Main exposing (main)
import Html exposing (Html)
import Html
import Process
import Task
import Debug
import Time
import Control exposing (Control)
import Control.Debounce as Debounce
main : Program Never Model Msg
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
type alias Model =
{ counter : Int
, state : Control.State Msg
}
init : ( Model, Cmd Msg )
init =
{ counter = 0, state = Control.initialState }
! [ incrementCounter ]
incrementCounter : Cmd Msg
incrementCounter = Cmd.map debounce <| delay (Time.second * 3) <| ContinuousDebouncing
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
type Msg
= Deb (Control Msg)
| ContinuousDebouncing
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Deb debMsg ->
Control.update (\s -> { model | state = s }) model.state debMsg
ContinuousDebouncing ->
let
x = Debug.log "ContinuousDebouncing"
in
( { model | counter = model.counter + 1 }, incrementCounter )
debounce : Msg -> Msg
debounce =
let
x = Debug.log "debounce"
in
Debounce.trailing Deb (3 * Time.second)
delay : Time.Time -> msg -> Cmd msg
delay time msg =
Process.sleep time
|> Task.andThen (always <| Task.succeed msg)
|> Task.perform identity
view : Model -> Html Msg
view model =
Html.text (toString model.counter)