Elm is a functional programming language that compiles JavaScript intended primarily for web application development, heavily emphasizing dependability and maintainability. While Elm is well-known for its powerful type system and ability to send data from Elm to JavaScript via ports, receiving data from JavaScript in Elm can be equally significant.
In this Answer, we will learn how to receive data from JavaScript to Elm using ports. We’ll use a simple example that involves clicking a button to receive a message from JavaScript to Elm. Here is a step-by-step process for building this example:
Model
The Model
represents an application’s current state. In our example, we’ll use a simple string to represent the data we want to receive from JavaScript to Elm.
-- Modeltype alias Model ={ dataReceived : String}
view
The view
function creates the HTML that is displayed on the page. We’ll make an HTML view with a “Receive Data from JS”
button and the text “No data received yet”
. When the user hits the button, it’ll change the text from “No data received yet”
to “Data from JavaScript”
.
-- Viewview : Model -> Html Msgview model =div [][ div [] [ text model.dataReceived ], button [ onClick (ReceiveData "Data from JavaScript") ] [ text "Receive Data from JS" ]]
update
functionThe update
function modifies the Model
in response to the messages it receives. In our application, the update
function will receive the dataFromJS
message and use a port to transfer the string “Data from JavaScript”
to Elm.
-- Updateupdate : Msg -> Model -> Modelupdate msg model =case msg ofReceiveData newData ->{ model | dataReceived = newData }
Ultimately, we’ll write an HTML page that loads the Elm app and updates a DOM element with data from Elm.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Elm and JavaScript Communication</title></head><body><div id="elm-container"></div><script src="elm.js"></script><script>var app = Elm.Main.init({node: document.getElementById('elm-container')});// Send data from JavaScript to Elmvar dataFromJS = "Data from JavaScript";app.ports.receiveData.send(dataFromJS);</script></body></html>
Here is the complete code to receive data from JavaScript in Elm.
{ "type": "application", "source-directories": [ "src" ], "elm-version": "0.19.0", "dependencies": { "direct": { "elm/browser": "1.0.2", "elm/core": "1.0.5", "elm/html": "1.0.0", "elm/json": "1.1.3" }, "indirect": { "elm/time": "1.0.0", "elm/url": "1.0.0", "elm/virtual-dom": "1.0.3" } }, "test-dependencies": { "direct": {}, "indirect": {} } }
Free Resources