如何在Elm中将`Msg`类型分成多种类型?

TPJ*_*TPJ 5 elm elm-architecture

在Elm中使用模型和更新的标准方法是定义Model和Msg类型以及更新函数:

type alias Model = { ... }

type Msg = Msg1 | Msg2 | ...

update : Msg -> Model -> (Model, Cmd Msg)
...
Run Code Online (Sandbox Code Playgroud)

当应用程序增长时,所有这些类型和功能变得更加复杂.我想以下列方式将它们分开:

type alias Model1 = { ... }
type alias Model2 = { ... }
type alias Model = { model1 : Model1, model2 : Model2 }

type Msg1 = Msg1a | Msg1b | ...
type Msg2 = Msg2a | Msg2b | ...
type Msg = M1 Msg1 | M2 Msg2 | ...
Run Code Online (Sandbox Code Playgroud)

然后,我想分别处理所有这些(我知道该怎么做).

不过,我的视图功能有问题.我将我的观点定义如下:

view : Model -> Html Msg
view model =
  let v1 = view1 model.model1
      ...
  in ...

view1 : Model1 -> Html Msg1
view1 model = ...
Run Code Online (Sandbox Code Playgroud)

问题是,view1的结果是Html Msg1,并且视图函数需要Html Msg.

有没有办法将结果转换Html Msg1Html Msg

Dog*_*ert 8

您正在寻找Html.map:

view : Model -> Html Msg
view model =
  let v1 = view1 model.model1 |> Html.map M1
      v2 = view2 model.model2 |> Html.map M2
  in ...
Run Code Online (Sandbox Code Playgroud)