Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created January 18, 2019 20:25
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 jc00ke/22ca49b0205b2e090e878dff845ab6df to your computer and use it in GitHub Desktop.
Save jc00ke/22ca49b0205b2e090e878dff845ab6df to your computer and use it in GitHub Desktop.
Console log JSON in Elm with ports
<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>
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