【问题标题】:Cancel subscriptions in Elm在 Elm 中取消订阅
【发布时间】:2016-08-01 22:12:45
【问题描述】:

我正在遵循 Elm 指南,并且我正尝试为时钟示例实现暂停按钮。在指南中是这样写的:

添加一个按钮来暂停时钟,关闭时间订阅。

我所做的只是为模型添加一个paused 属性并在更新函数中使用它。我应该如何取消订阅?

module Main exposing (..)

import Html exposing (Html)
import Html.App as App
import Html.Events exposing (onClick)
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)


main =
    App.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }


type alias Model =
    { time : Time
    , paused : Bool
    }


init : ( Model, Cmd Msg )
init =
    ( Model 0 False, Cmd.none )


type Msg
    = Tick Time
    | Toggle


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Tick newTime ->
            if not model.paused then
                ( Model newTime False, Cmd.none )
            else
                ( model, Cmd.none )

        Toggle ->
            ( Model model.time (not model.paused), Cmd.none )


subscriptions : Model -> Sub Msg
subscriptions model =
    Time.every second Tick


clock : Time -> Html Msg
clock time =
    let
        sAngle =
            turns (Time.inMinutes time)

        sHandX =
            toString (50 + 40 * cos sAngle)

        sHandY =
            toString (50 + 40 * sin sAngle)
    in
        svg [ viewBox "0 0 100 100", width "300px" ]
            [ circle [ cx "50", cy "50", r "45", fill "#0B79CE" ] []
            , line [ x1 "50", y1 "50", x2 sHandX, y2 sHandY, stroke "#023963" ] []
            ]


view : Model -> Html Msg
view model =
    let
        btnText =
            if model.paused then
                "Start"
            else
                "Pause"
    in
        Html.div []
            [ clock model.time
           , Html.button [ onClick Toggle ] [ Html.text btnText ]
           ]

【问题讨论】:

  • 与其取消订阅,为什么不在订阅函数内部检查模型是否暂停和 noop(返回空操作或任何需要的操作)?
  • 显然是这样,谢谢

标签: elm


【解决方案1】:

我想你可以简单地返回 Sub.none 而不是 subscription 函数暂停时。

如果您选择这样做,那么您可以还原 Tick 处理程序在您的 update 函数中。

subscriptions : Model -> Sub Msg
subscriptions model =
    if model.paused
    then Sub.none
    else Time.every second Tick

【讨论】:

  • 我完全跳过了订阅的模型参数!谢谢
猜你喜欢
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 2022-01-19
  • 2017-12-18
  • 2012-03-14
  • 2016-07-27
相关资源
最近更新 更多