2

I've been struggling with how to organize my code in Elm, and after some googling I found this. It's not that recent but I've tried it and the result is pretty nice, compared to what I used to have. But trying to apply this to my states I find myself wanting to create empty Cmd just to send an Msg to the "root" update function, to transition from one State to the other. That doesn't seem right, I assume I'm just doing it wrong.

So let's say I have this:

type alias Model =
  { state : State
  }

type State = StateProjectList ProjectList.Types.Model
           | StateProjectView ProjectView.Types.Model

type Msg = ProjectList ProjectList.Types.Msg
         | ProjectView ProjectView.Types.Msg
         | TransitionProjectView Project

When I'm in StateProjectList, I need to be able to transition to a StateProjectView somehow but it's view function returns a ProjectList.Types.Msg and not a regular Msg. One idea I've come up with would be to create an empty Cmd that would call back using TransitionProjectView, which doesn't seem right.

The other idea would be to use a Msg like ProjectList TransitionToProjectView and match that first in the root update function, not sure about that long term though.

I did see the note on Cmd.map's doc saying if you need this you're probably doing something wrong, unfortunately the link explaining what to do instead is dead. What would be the proper way to either transition from one state to the other, or a better architecture if this whole thing is wrong?

4

1 回答 1

4

这通常使用路由来完成。我还没有迁移到 0.19,这稍微改变了导航的细节,但我认为 0.19 中的基本思想与 0.18 中的基本思想相同。为您的路由生成一个 URL 并使用该 URL 呈现一个链接,或者使用Navigation.modifyUrl0.18 中的“elm-lang/navigation”或0.19 中的Browser.Navigation.pushUrlfromelm/browser以编程方式修改 URL,它们都返回一个Cmd msg.

您很可能还需要某种基于自定义类型的框架,以便获得类型安全的路由,而不是直接处理原始字符串 URL。

阅读有关导航URL 解析的指南页面是一个好的开始。在Elm SPA 示例中查看事情是如何完成的总是一个好主意。

如果由于某种原因您不想使用路由,则ProjectList TransitionToProjectView在根更新功能中进行匹配似乎是一种不错的方法。Html.map或者,您可以让父级向子级传递一个函数,而不是使用 将 msg 包装在父级中,Child.Model -> Msg子级可以使用该函数自己包装其消息,从而也可以直接使用其父级消息。

于 2018-09-24T17:09:45.180 回答