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 ?

4

1 回答 1

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 )
于 2018-10-12T22:56:48.353 回答