Skip to content

Instantly share code, notes, and snippets.

@aravindavk
Last active June 23, 2016 13:33
Show Gist options
  • Save aravindavk/cddc32bea712485de56c9962b44f2e73 to your computer and use it in GitHub Desktop.
Save aravindavk/cddc32bea712485de56c9962b44f2e73 to your computer and use it in GitHub Desktop.
elm-lang JS port Example - Sending Elm Record as JS Object

Simple JS function which accepts user object and returns "NAME".

JS file generated using,

elm-make Main.elm --output app.js

Can be minified using Google Closure compiler,

java -jar compiler.jar -O ADVANCED --language_in ECMASCRIPT5 \
    --jscomp_off globalThis --js app.js --js_output_file app.min.js

Issue: Google Closure compiler renames user object while sending it to JS. This example will not work with app.min.js. Console.log when app.min.js is used.

Object { name: "Aravinda", aa: "[email protected]", Y: "" }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
function convert(user){
return user.name + "<" + user.email + ">";
}
var app = Elm.Converter.fullscreen();
app.ports.converter.subscribe(function(user) {
console.log(user);
var out = convert(user);
app.ports.converted_text.send(out);
});
</script>
</html
-- ELM VERSION 0.17.0
port module Converter exposing (..)
import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
-- MAIN
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ name : String
, email : String
, output : String
}
-- MSG
type Msg =
AddUserName String
| AddUserEmail String
| Format
| Output String
-- INIT
init : (Model, Cmd Msg)
init =
(Model "" "" "", Cmd.none)
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
AddUserName txt ->
( {model | name = txt }, Cmd.none )
AddUserEmail txt ->
( {model | email = txt }, Cmd.none )
Format ->
( model, converter model )
Output txt ->
( { model | output = txt }, Cmd.none )
-- OUTGOING PORT
port converter : Model -> Cmd msg
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ placeholder "Name", onInput AddUserName ] []
, input [ placeholder "Email", onInput AddUserEmail ] []
, button [ onClick Format ] [ text "Format" ]
, div [] [ text model.output ]
]
-- INCOMING PORT
port converted_text : (String -> msg) -> Sub msg
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
converted_text Output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment