In this Answer, we will learn how to send data from Elm to JavaScript using ports. Ports provide a way to communicate with JavaScript code. We'll use a simple example that involves clicking a button to send a message from Elm to JavaScript. Here is a step-by-step process for building this example:
Model
The Model
represents the current state of an application. For our example, we'll use a simple string to represent the data we want to send to JavaScript.
type alias Model =String
view
The view
function generates the HTML that is rendered on the webpage. We'll create a view displaying a "Send to JavaScript" button. We'll also define a message type called DataToJS
, which will be sent to the update function when the user clicks the button.
view : Model -> Html Msgview model =div [][ button [ onClick DataToJS ][ text "Send a message to JS" ]]
update
functionThe update
function changes the model based on the messages it receives. In our case, the update
function will receive the DataToJS
message and send the string "1+1 = 2!" to JavaScript using a port.
update : Msg -> Model -> ( Model, Cmd Msg )update msg model =case msg ofDataToJS ->( model, sendData "1+1 = 2!" )
We'll define a port called sendData
that takes a string as an argument and sends it to JavaScript.
port sendData : String -> Cmd msg
Finally, we will create an HTML file that loads the Elm app and updates a DOM element with the data sent from Elm. We will follow the steps below:
Create a div
that loads the Elm app.
To run the compiled Elm code, include the elm.js
file.
Add the JavaScript code for receiving the data sent by the Elm app.
To display the data received from Elm on the webpage, use the subscribe
function to listen to the sendData
port.
<!DOCTYPE html><html><body><div id="load-elm-code"></div><div id="data-from-elm"></div><script src="elm.js"></script><script>var elmApp = Elm.Main.init({node: document.getElementById("load-elm-code")});elmApp.ports.sendData.subscribe(function(data) {var output = document.getElementById("data-from-elm");output.innerHTML = "Data from Elm: " + data;});</script></body></html>
Now, let's look at the example where we have a button that, when clicked, will send data from Elm to JavaScript.
<!DOCTYPE html> <html> <body> <div id="load-elm-code"></div> <div id="data-from-elm"></div> <script src="elm.js"></script> <script> var elmApp = Elm.Main.init({ node: document.getElementById("load-elm-code") }); elmApp.ports.sendData.subscribe(function(data) { var output = document.getElementById("data-from-elm"); output.innerHTML = "Data from Elm: " + data; }); </script> </body> </html>
After executing the code above, click the "Send a message to JS" button. Once clicked, we should see the message "Data from Elm: 1+1 = 2!" on the webpage, as shown in the illustration below.
Free Resources