Search code examples
javascriptnestedelmports

Elm: Ports not working in nested modules


I'm trying to get ports working in a nested module, by adapting a working example to be nested. In this case Save2.elm calls fileSelected, a JavaScript function. However, this does not work.

Debugging shows that the message "Json Selected" is fired. Unfortunately, the JavaScript function never gets called. The defined port in Ports.elm:

port fileSelected : String -> Cmd msg

Relevant part of Save2.elm, the "Json Selected" part is fired:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        JsonSelected inputBoxId ->
            ( model
            , fileSelected inputBoxId
            )

The relevant JavaScript part:

<script src="main.js"></script>
<script>
    var app = Elm.Main.fullscreen();
    // This log is shown from start-up
    console.log("Upload.html console.log is shown")
    app.ports.fileSelected.subscribe(function (id) {
      // This log is never shown
      console.log("fileSelected is executed")

A link to the repo: https://github.com/gitLabor8/Elm-Ports-not-working-in-nested-modules

Thanks in advance,


Solution

  • In your repo, the Cmd from Save2.update is just ignored in Main.update.

    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            Save2 saveMsg ->
                ( { model | save2 = Tuple.first (Save2.update saveMsg model.save2) }
                , Cmd.none
                )
    

    You need to return it from Main.update so that Elm runtime can handle the Cmd.

    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            Save2 saveMsg ->
                let
                    ( save2Model, save2Cmd )
                        = Save2.update saveMsg model.save2
                in
                    ( { model | save2 = save2Model }
                    , save2Cmd
                    )
    

    In Elm, calling port functions don't trigger anything. They just return Cmds that have to be handled by Elm runtime.