Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Created January 20, 2018 13:20
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 ryuheechul/846f97c3fe3e3babd4e174bbf9a10ad7 to your computer and use it in GitHub Desktop.
Save ryuheechul/846f97c3fe3e3babd4e174bbf9a10ad7 to your computer and use it in GitHub Desktop.
Elm (0.18) program ports example
port module Echo exposing (..)
import Platform exposing (program, Program)
import Json.Decode
-- importing Json.Decode is necessary for now because of https://github.com/elm-lang/elm-make/issues/127
---- MODEL ----
type alias Model =
{ crap : String }
init : ( Model, Cmd Msg )
init =
( { crap = "" }, Cmd.none )
---- UPDATE ----
type Msg
= Listen String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Listen crap ->
( Model crap, echo crap )
port listen : (String -> msg) -> Sub msg
port echo : String -> Cmd msg
---- Subscriptions ----
subscriptions : Model -> Sub Msg
subscriptions model =
listen Listen
---- PROGRAM ----
main : Program Never Model Msg
main =
program
{ init = init
, update = update
, subscriptions = subscriptions
}
import { Echo } from './Echo.elm'
const echoer = Echo.worker()
export function startListening(listener = console.log) {
echoer.ports.echo.subscribe(listener)
}
export function shout(msg) {
echoer.ports.listen.send(msg)
}
import { shout, startListening } from './echo';
startListening(console.log)
shout('hi')
shout('good bye')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment