我如何获得Elm 0.17 / 0.18的当前时间?

时间:2016-06-24 20:40:23

标签: functional-programming elm frp

我已经问过这个问题了:
How do I get the current time in Elm?

通过编写我自己的(现已弃用的)start-app变体来回答:
<击> http://package.elm-lang.org/packages/z5h/time-app/1.0.1

当然,榆树建筑已经发生了变化,我旧的做事方式不再有效,因为没有信号或Time.timestamp

...所以

假设我使用标准更新功能签名构建应用程序:
update : Msg -> Model -> (Model, Cmd Msg)

我想用更新时间给我的模型添加时间戳。一个不可接受的几乎解决方案是订阅Time.every。从概念上讲,这不是我想要的。这是随着时间更新模型,也是用消息单独更新模型。

我想要的是能够写一个带签名的更新功能:
updateWithTime : Msg -> Time -> Model -> (Model, Cmd Msg)

我开始尝试通过添加一些额外消息来解决这个问题:
Msg = ... When | NewTime Time

创建新命令:
timeCmd = perform (\x -> NewTime 0.0) NewTime Time.now

所以在任何动作中,我都可以发出一个额外的命令来检索时间。但是这很快就会变得混乱和失控。

关于我如何清理它的任何想法?

6 个答案:

答案 0 :(得分:9)

无需在每个更新路径上执行时间提取的一个选项是将Msg包装在另一种消息类型中,该消息类型将获取时间,然后随时间调用正常update。这是http://elm-lang.org/examples/buttons的修改版本,它将在每次更新时更新模型的时间戳。

import Html exposing (div, button, text)
import Html.App exposing (program)
import Html.Events exposing (onClick)
import Task
import Time exposing (Time)


main =
  program { init = (Model 0 0, Cmd.none), view = view, update = update, subscriptions = (\_ -> Sub.none) }

type alias Model =
  { count: Int
  , updateTime : Time
  }

view model =
  Html.App.map GetTimeAndThen (modelView model)

type Msg
  = GetTimeAndThen ModelMsg
  | GotTime ModelMsg Time

update msg model =
  case msg of
    GetTimeAndThen wrappedMsg ->
      (model, Task.perform (\_ -> Debug.crash "") (GotTime wrappedMsg) Time.now)

    GotTime wrappedMsg time ->
      let
        (newModel, cmd) = modelUpdate wrappedMsg time model
      in
        (newModel, Cmd.map GetTimeAndThen cmd)

type ModelMsg = Increment | Decrement

modelUpdate msg time model =
  case msg of
    Increment ->
      ({model | count = model.count + 1, updateTime = time}, Cmd.none)

    Decrement ->
      ({model | count = model.count - 1, updateTime = time}, Cmd.none)

modelView model =
  div []
    [ button [ onClick  Decrement ] [ text "-" ]
    , div [] [ text (toString model.count) ]
    , button [ onClick  Increment ] [ text "+" ]
    , div [] [ text (toString model.updateTime) ]
    ]

答案 1 :(得分:8)

我发现我认为比接受的答案更优雅的解决方案。 GetTimeAndThen消息不是拥有两个单独的模型,而是拥有一个返回消息的处理程序。代码感觉更自然,更像榆树,可以更通用的方式使用:

module Main exposing (..)

import Html exposing (div, button, text)
import Html.App as App
import Html.Events exposing (onClick)
import Task
import Time exposing (Time)


main =
    App.program
        { init = ( Model 0 0, Cmd.none )
        , view = view
        , update = update
        , subscriptions = (\_ -> Sub.none)
        }


view model =
    div []
        [ button [ onClick decrement ] [ text "-" ]
        , div [] [ text (toString model) ]
        , button [ onClick increment ] [ text "+" ]
        ]


increment =
    GetTimeAndThen (\time -> Increment time)


decrement =
    GetTimeAndThen (\time -> Decrement time)


type Msg
    = Increment Time
    | Decrement Time
    | GetTimeAndThen (Time -> Msg)


type alias Model =
    { count : Int, updateTime : Time }


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        GetTimeAndThen successHandler ->
            ( model, (Task.perform assertNeverHandler successHandler Time.now) )

        Increment time ->
            ( { model | count = model.count + 1, updateTime = time }, Cmd.none )

        Decrement time ->
            ( { model | count = model.count - 1, updateTime = time }, Cmd.none )


assertNeverHandler : a -> b
assertNeverHandler =
    (\_ -> Debug.crash "This should never happen")

答案 2 :(得分:7)

elm-0.18完整示例https://runelm.io/c/72i

import Time exposing (Time)
import Html exposing (..)
import Html.Events exposing (onClick)
import Task

type Msg
    = GetTime
    | NewTime Time

type alias Model =
    { currentTime : Maybe Time
    }

view : Model -> Html Msg
view model =
    let
        currentTime =
            case model.currentTime of
                Nothing ->
                    text ""

                Just theTime ->
                    text <| toString theTime
    in
        div []
            [ button [ onClick GetTime ] [ text "get time" ]
            , currentTime
            ]

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        GetTime ->
            model ! [ Task.perform NewTime Time.now ]

        NewTime time ->
            { model | currentTime = Just time } ! []

main : Program Never Model Msg
main =
    program
        { init = init
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }

init : ( Model, Cmd Msg )
init =
    { currentTime = Nothing } ! []

答案 3 :(得分:3)

在关于Slack的这个问题的讨论之后,这里是Msg中没有函数的替代实现。与接受的答案一样,只有在Time.now Task成功时才会更新模型。

import Html exposing (div, button, text)
import Html.App as App
import Html.Events exposing (onClick)
import Task
import Time exposing (Time)


main =
    App.program
        { init = init
        , view = view
        , update = update
        , subscriptions = (\_ -> Sub.none)
        }


view model =
    div []
        [ button [ onClick Decrement ] [ text "-" ]
        , div [] [ text (toString model) ]
        , button [ onClick Increment ] [ text "+" ]
        ]


type Msg
    = NoOp
    | Increment 
    | Decrement
    | GetTimeSuccess Msg Time
    | GetTimeFailure String


type alias Model =
    { count : Int, updateTime : Result String Time }

init : (Model , Cmd Msg)
init = 
  ( { count = 0
    , updateTime = Err "No time yet!"
    }
  , Task.perform  GetTimeFailure  (GetTimeSuccess NoOp) Time.now
  )


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp -> (model, Cmd.none)

        Increment ->
            ( model
            , Task.perform  GetTimeFailure  (GetTimeSuccess Increment) Time.now
            )

        Decrement ->
            ( model
            , Task.perform  GetTimeFailure (GetTimeSuccess Decrement) Time.now
            )


        GetTimeSuccess Increment time ->
            ( { model | count = model.count + 1, updateTime = Ok time}
            , Cmd.none
            )

        GetTimeSuccess Decrement time ->
            ( { model | count = model.count - 1, updateTime = Ok time}
            , Cmd.none
            )            

        GetTimeSuccess _ time ->
            ( { model |  updateTime = Ok time}
            , Cmd.none
            )

        GetTimeFailure msg ->
            ( { model | updateTime = Err msg}
            , Cmd.none
            )

答案 4 :(得分:2)

我对自己的问题有答案(基于amilner42的建议)。我在当前的代码中使用此解决方案。

我非常喜欢@ w.brian的解决方案,但是消息中的函数会破坏调试器 我喜欢@robertjlooby的解决方案,这是非常相似的,虽然它不需要额外的类型,并且更新为0.18。

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            model ! []

        TickThen msg ->
            model ! [ Task.perform (Tock msg) Time.now ]

        Tock msg time ->
                updateTimeStampedModel msg { model | time = time }

        otherMsg ->
            update (TickThen msg) model


updateTimeStampedModel : Msg -> Model -> ( Model, Cmd Msg )
updateTimeStampedModel msg model =
    case msg of
        NoOp ->
            update msg model

        TickThen _ ->
            update msg model

        Tock _ _ ->
            update msg model

        -- ALL OTHER MESSAGES ARE HANDLED HERE, AND ARE CODED TO ASSUME model.time IS UP-TO-DATE.

答案 5 :(得分:1)

您可以创建一个Native模块,然后公开一个timestamp函数,该函数从JavaScript中Date.now()获取时间。

这大概就是它的样子:

Timestamp.elm

module Timestamp exposing (timestamp)

import Native.Timestamp

timestamp : () -> Int
timestamp a = Native.Timestamp.timestamp a

本地/ Timestamp.js

var _YourRepoUserName$your_repo$Native_Timestamp = function() {
  return { timestamp: function(a) {return Date.now()}
}

Main.elm

port module Main exposing (..)

import Timestamp exposing (timestamp)

然后你可以在Elm的任何地方使用(timestamp ())来获取当前时间戳作为Int。

注意:我使用了timestamp : () -> Int因为我无法让它工作。 timestamp : Int只返回首次加载的硬编码时间。

如果可以改进,请告诉我。