Separate concerns with messages

80 Views Asked by At

I'm trying to make a generic modal that takes as parameters a text to show and an event to send on the onClick of the accept button.

There is a cancel button, which shares the hiding functionality with the accept button.

So I tried to send 2 events on the onClick of the accept. One for the accept logic and one for the hiding logic. And that's not working, just the first event is working.

I tried another strategy, the hidden event might have an event OnHideModal (Maybe Msg) so the modal merges both events before the accept and the OnHide hides the modal and sends the internal event to continue the processing. This seems to me too heavy, because if you have 3 or more logic events all your events must have another Maybe Msg. And I have difficulties making a Cmd Msg with the internal events.

It seems peoples advise is to make a HideAndLogic event but that would lead to a lot of copying and pasting of the hiding code, one for each logic. Plus the logic would be tied with the hiding logic which would make it harder to understand. And if I want to send an event for the logic without hiding anything I would have to make another event that copies half the logic of the first. That goes against basic programming good practice, so I think some people maybe have found a better way. A way that allows these separate logics to be really separated even in progenitor events.

Using Elm 0.18

1

There are 1 best solutions below

5
On

I think you are making this too complicated. You need:

viewModal : msg -> msg -> Html msg 
viewModal  acceptMsg  cancelMsg = 
  div [] [ ... button [onclick acceptMsg] ...
           ... button [onclick cancelMsg] ...
         ]

Then, your main model needs a shouldShowModal : Bool, or some other way of deciding if it should show the modal.
The modal will trigger a Msg which you will handle in your event loop.