Created
January 18, 2019 20:25
-
-
Save jc00ke/22ca49b0205b2e090e878dff845ab6df to your computer and use it in GitHub Desktop.
Console log JSON in Elm with ports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style> | |
/* you can style your program here */ | |
</style> | |
</head> | |
<body> | |
<main></main> | |
<script> | |
var app = Elm.Main.init({ node: document.querySelector('main') }) | |
app.ports.jsonConsole.subscribe(function(json) { | |
console.log(json) | |
}) | |
// you can use ports and stuff here | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
port module Main exposing (main) | |
import Browser | |
import Html exposing (Html, button, div, text) | |
import Html.Events exposing (onClick) | |
import Json.Encode as E exposing (Value, int, object, string) | |
type alias Model = | |
{ count : Int | |
, name : String | |
} | |
initialModel : Model | |
initialModel = | |
{ count = 0 | |
, name = "Foo" | |
} | |
encodeModel : Model -> Value | |
encodeModel model = | |
object | |
[ ( "count", int model.count ) | |
, ( "name", string model.name ) | |
] | |
port jsonConsole : Value -> Cmd msg | |
type Msg | |
= ConsoleLogJson | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
ConsoleLogJson -> | |
let | |
json = | |
encodeModel model | |
in | |
( model, jsonConsole json ) | |
view : Model -> Html Msg | |
view model = | |
div [] [ button [ onClick ConsoleLogJson ] [ text "Log to console" ] ] | |
subscriptions : Model -> Sub Msg | |
subscriptions _ = | |
Sub.batch [] | |
init : () -> ( Model, Cmd msg ) | |
init flags = | |
( initialModel, Cmd.none ) | |
main : Program () Model Msg | |
main = | |
Browser.element | |
{ init = init | |
, subscriptions = subscriptions | |
, view = view | |
, update = update | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment