[beginner] general msg/update

I don’t know much about elm architecture internally but can we just have one general msg/update like:

type Msg m = Upd (m -> m)

update msg model =
  case msg of
    Upd f -> f model

and then used in all views without having to specify actions in two other places like:

view model =
  div []
    [ button [ onClick (Upd (\m->m-1)) ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick (Upd (\m->m+1)) ] [ text "+" ]
    ]

i found it works even in more complex cases so I’m wondering if I’m missing anything.thanks

2 Likes

This will work fine, but has some important drawbacks, namely:

  1. The built in debugger won’t work very well, since functions can’t be serialized. As such it is recommended to only have data (i.e. not functions) in msgs or models.
  2. You are mixing business logic and view logic together. This tends to lead to messy code. The recommended way essentially follows the MVC pattern pretty strictly, which is a pattern that works well for most apps.
6 Likes

Msg types should not contain functions. This is possible with 0.18 but I would not be surprised to see it become invalid in future releases.

You can still use this pattern by simply updating the model in the view and sending the new model with the Upd

type Msg = Upd Model

update msg model =
  case msg of
    Upd newModel -> newModel

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

If updating it like this is too expensive, consider switching strategies.

I don’t think this is sound advice, since you now have the potential problem of the model being out of sync or other timing and ordering issues.

It depends on the model. I would not use this for complex models but for simple models it should work perfectly fine.

This is the approach used in elm-sortable-table.

In more or less complicated apps the model changing functions are long and can’t be inlined. View function will just turn into mess. I can’t see a single benefit of this approach. Having drawbacks @gampleman mentioned in mind I would say this is definitely an anti-pattern.

@pdamoc I can’t find an example of this approach in elm-sortable-table. Were you referring to the latest version?

Yes, it is in the latest version but the code is not as explicit as I made it to be. You have to investigate how the State changes based on events in the widget (sorting) in order to figure it out.

1 Like