Skip to content

Instantly share code, notes, and snippets.

@SirmaXX
Last active August 18, 2019 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SirmaXX/4876df1cb197510da866385a15162123 to your computer and use it in GitHub Desktop.
Save SirmaXX/4876df1cb197510da866385a15162123 to your computer and use it in GitHub Desktop.
elm ports thanks for attention @mzero example from :https://elmprogramming.com/
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main</title>
<script src="main.js"></script>
</head>
<body>
<div id="elm"></div>
<script>
var app = Elm.Main.init({
node: document.getElementById('elm')
});
app.ports.sendData.subscribe(function(data) {
localStorage.setItem('cache', JSON.stringify(data));
console.log(data);
app.ports.receiveData.send("Hey Elm!");
});
</script>
</body>
</html>
port module Main exposing (..)
import Html exposing (..)
import Html.Events exposing (..)
import Browser
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
type alias Model =
String
type Msg
= SendDataToJS
| ReceivedDataFromJS Model
port sendData : String -> Cmd msg
port receiveData : (Model -> msg) -> Sub msg
init : () -> (Model, Cmd Msg)
init _ =
( "", Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SendDataToJS ->
( model, sendData "Hello JavaScript!" )
ReceivedDataFromJS data ->
( data, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
receiveData ReceivedDataFromJS
view : Model -> Html Msg
view model =
div []
[ button [ onClick SendDataToJS ]
[ text "Send Data to JavaScript" ]
, br [] []
, br [] []
, text ("Data received from JavaScript: " ++ model)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment