Skip to content

Instantly share code, notes, and snippets.

@artronics
Created September 14, 2016 21:36
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 artronics/af21d2fcdc712f5de0e914d3d5f9d98e to your computer and use it in GitHub Desktop.
Save artronics/af21d2fcdc712f5de0e914d3d5f9d98e to your computer and use it in GitHub Desktop.
Inter-Component Communication in 0.17 as discussed https://groups.google.com/forum/?fromgroups#!topic/elm-discuss/i99LBvYSkpY
module ChildOne exposing (..)
import Ports exposing (..)
import Html exposing (Html, button, text)
import Html.Events exposing (onClick)
type alias Model = String
type Msg
= Click
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Click ->
( model, dispatchSomeMessage "Hello World!" )
view : Model -> Html Msg
view model =
button [ onClick Click ] [text "Click Me"]
module ChildTwo exposing (..)
import Ports exposing (..)
import Html exposing (Html, text)
type alias Model =
{ message : String }
type Msg
= ChangeMessage String
subscriptions : Model -> Sub Msg
subscriptions model =
receiveSomeMessage ChangeMessage
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ChangeMessage msg ->
({ model | message = msg }, Cmd.none )
view : Model -> Html Msg
view model =
text model.message
var app = Elm.Main.fullscreen();
app.ports.dispatchSomeMessage.subscribe(function(msg) {
app.ports.receiveSomeMessage.send(msg);
});
module Main exposing (..)
import ChildOne
import ChildTwo
type alias Model =
{ childOneModel : ChildOne.model
, childTwoModel : ChildTwo.model
}
-- ..init func. nothing special here.
type Msg
= ChildOneMsg ChildOne.Msg
| ChildTwoMsg ChildTwo.Msg
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Sub.map ChildOneMsg (ChildOne.subscriptions model. childOneModel)
, Sub.map ChildTwoMsg (ChildTwo.subscriptions model. childTwoModel)
]
-- .. update function. nothing special here.
main : Program Never
main =
Html.App.program
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
port module Ports exposing (..)
-- dispatchSomeMessage will create a command with a
-- string payload representing an important message
-- to broadcast to listening components.
port dispatchSomeMessage : String -> Cmd msg
-- receiveSomeMessage is the port which our components
-- subscribe to receive the dispatched message
port receiveSomeMessage : (String -> msg) -> Sub msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment