Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the `Msg` type be separated into many types in Elm?

The standard way to use model and update in Elm is to define the Model and Msg types, and the update function:

type alias Model = { ... }

type Msg = Msg1 | Msg2 | ...

update : Msg -> Model -> (Model, Cmd Msg)
...

When the application grows, all those types and functions become more complex. I'd like to separate them in the following way:

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 | ...

Then, I'd like to handle all of them separately (and I know how to do it).

I have a problem with the view function, though. I define my view as follows:

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

view1 : Model1 -> Html Msg1
view1 model = ...

The problem is, the result of view1 is Html Msg1, and the view function needs Html Msg.

Is there a way to convert the result from Html Msg1 to Html Msg?

like image 851
TPJ Avatar asked May 09 '18 05:05

TPJ


1 Answers

You're looking for Html.map:

view : Model -> Html Msg
view model =
  let v1 = view1 model.model1 |> Html.map M1
      v2 = view2 model.model2 |> Html.map M2
  in ...
like image 67
Dogbert Avatar answered Sep 16 '22 20:09

Dogbert