1

I have an update function that adds an Answer to a Question

Once the question has been updated with an answer, I'd like to send it to an outgoing port, while also updating my model.

port emitQuestion : Question -> Cmd msg

update msg model =
  AnswerQuestion answer ->
    case model.question of
      Nothing ->
        ( model, Cmd.none)

      Just question ->
        let 
          updatedQuestion = 
            { question | answer = Just answer }
        in
          ( { model | question = updatedQuestion } , Cmd.none)

How could I pass updatedQuestion to emitQuestion in this scenario ?

glennsl
  • 28,186
  • 12
  • 57
  • 75
Denim Demon
  • 734
  • 1
  • 10
  • 23

1 Answers1

2

You define the outgoing port signature, but without a body, like this:

port questionUpdated : Question -> Cmd msg

(assuming that you have an Question type or alias; your question didn't specify)

Then, in the calling javascript, you define your port handler after calling Elm init:

var app = Elm.Main.init({ node: document.querySelector('main') })
app.ports.questionUpdated.subscribe(function(data) {
  // your javascript for handling updated question
});

To pass that new question value to the port on update, just pass it in the second value of the return type from update:

( { model | question = updatedQuestion } , questionUpdated updatedQuestion )
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • Thanks for responding so quickly. Unfortunately I asked my question poorly. I'm wondering that once I have checked I have a question and have updated it with the answer `updatedQuestion = { question | answer = Just answer }` - how can I then send this to the emitQuestion port, while also saving it to the model? – Denim Demon Oct 12 '18 at 23:40