Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send multiple messages on one event using elm-html?

Tags:

elm

I would like to send two messages to distinct adresses on one event. Particular case I encountered was that I had a some popup and when user clicks "Add" I would like to:

  • Close the popup (message send to popup component)
  • Inform parent component that item should be added (message send to parent component)

onClick has following type "Address a -> a -> Attribute" some there seems to be no possibility to do that. On the other hand it seems like such pattern (one action resulting in multiple message) would be often met in practice.

For now I resorted to sending one message informing parent about item added and then parent in update function updates popup with Hide action.

addButton = button [onClick context.addTaskAddress model.taskDescription] [text "Add"]

and then in parent's component update function

popup = AddTaskPopup.update AddTaskPopup.Hide model.popup
like image 613
Artur Krajewski Avatar asked Feb 06 '16 15:02

Artur Krajewski


1 Answers

You could set up an intermediate proxy mailbox that takes a list of address and message pairs, then call that from the button click.

proxy : Mailbox (List (Address a, a))
proxy =
  mailbox []

Then you could have a broadcast signal which listens to the proxy mailbox and creates a bunch of Signal.send tasks to notify other addresses.

port broadcast : Signal (Task x (List ()))
port broadcast =
  let
    tasks = List.map (uncurry Signal.send)
  in
    Signal.map (Task.sequence << tasks) proxy.signal

Your onClick code would then look something like this, where you pass in the list of address and Action pairs:

onClick proxy.address [(address, Action1), (address, Action2)]

Note that in the above code, address refers to the address coming into the view function, whereas proxy.address refers to the proxy mailbox we just set up.

This is a general purpose solution that will work for any number of signals.

like image 109
Chad Gilbert Avatar answered Jan 02 '23 20:01

Chad Gilbert