Elm Language Incoming


Example

Incoming data from JavaScript is going through Subscriptions.

Elm side

First, we need to define an incoming port, using the following syntax:

port input : (Int -> msg) -> Sub msg

We can use Sub.batch if we have multiple subscriptions, this example will only contain one Subscription to input port

subscriptions : Model -> Sub Msg
subscriptions model =
    input Get

Then you have to pass the subscriptions to your Html.program:

main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

JavaScript side

Initialize the application:

var root = document.body;
var app = Elm.Main.embed(root);

Send the message to Elm:

var counter = 0;
        
document.body.addEventListener('click', function () {
    counter++;
    app.ports.input.send(counter);
});

Note

Please note, that as of 0.17.0 the immediate app.ports.input.send(counter); after app initialization will have no effect!

Pass all the required data for the start-up as Flags using Html.programWithFlags