Elm 架构和任务

Elm Architecture and tasks

UPDATEElm Architecture 文档中已对此进行了介绍。

--

我不明白你是如何将 Elm 架构和任务联系起来的。

-- Action is an enumeration of possible actions
type Action = ..

-- Model is a Model that evolves in time
model : Signal Model

-- View turns a model into Html, potentially sending actions to an address
view : Address Action -> Model -> Html

-- Update turns a model and an action into another model
update : Action -> Model -> Model

-- Main waits for new values of the model to be emitted, and pass then to the view action
main : Signal Html
main =
  Signal.map (view actions.address) model

我正在尝试对此建模:

这是正确的方法吗?

我应该更改哪些功能(更新、主要)?

我明白这是在暗示什么here,但是解释的不太清楚,我不明白需要更改什么。

因此欢迎任何完整的示例/或更多解释。

编辑:

此处提供更完整的版本("kinda" 有效):http://share-elm.com/sprout/55bf3c3ce4b06aacf0e8ba17

看来,我离它的工作还有几步之遥,因为当我单击按钮时任务并不总是 运行(但希望我能到达某个地方。)

虽然很可能在按下按钮时执行任务,但通常并不需要。您可能想要的是向 Action 信号发送消息,然后更新模型,然后视图可能会更改。这是标准的 Elm 架构。

如果您真的想执行任务,您可以执行以下操作:

type Action = NoOp | ButtonClicked | SetText String

type alias Model =
  { tasks : Task Http.Error String
  , text : String
  }

init : Model
init =
  { task = Task.succeed "Fetching..."
  , text = ""
  }

-- We can use, for example, the Http.get task
update : Action -> Model -> Model
update action model =
  case action of
    ButtonClicked ->
      { model | task <-
        Http.getString "http://example.org/some-text.txt"}
    SetText t ->
      { model | text <- t }
    _ -> model

view : Address Action -> Model -> Html
view address model =
  div []
   [ div
      [ class "btn btn-default"
      , onClick address ButtonClicked
      ]
      [ text "Click me!" ]
   , h3 "Here is what was fetched:"
   , p [] [ text model.text ]
   ]

-- now possibly in another file

actions : Signal.Mailbox Action
actions : Signal.mailbox NoOp    

model : Signal Model
model = Signal.foldp init update actions.signal

-- This is what actually performs the Tasks
-- The Elm task example also details how to send
port taskPort : Signal (Task Http.Error String)
port taskPort =
  ((.task) <~ model) `andThen`
    (Signal.send actions.address << SetText)

main : Signal Html
main = view actions.address <~ model

请注意,如果您只想在任务更改时执行任务,可以使用Signal.dropRepeats

方法是将模型更新映射到 response 信号,该信号接收您希望模型做出反应的结果。

视图将任务发送到 query/requests 邮箱。

端口将是执行任务andThen 的查询信号上的映射,将结果发送到response 邮箱。

如果您想实际查看此文件,请查看此文件(我已突出显示相关部分)

https://github.com/pdamoc/elmChallenges/blob/master/challenge4.elm#L72-L94

请注意,您所看到的比您需要的要复杂一点,因为它还实现了一种机制,仅在用户停止输入时才执行任务。

这在文档中得到了回答:

https://github.com/evancz/elm-architecture-tutorial#user-content-example-5-random-gif-viewer