Skip to content

Instantly share code, notes, and snippets.

@ream88
Created July 20, 2017 19:45
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 ream88/c076814d3936a8a70f89ff5eb120276f to your computer and use it in GitHub Desktop.
Save ream88/c076814d3936a8a70f89ff5eb120276f to your computer and use it in GitHub Desktop.
Elm communication
module Child1 exposing (Msg(..), Model, init, update)
import WebData exposing (..)
type Msg
= Response (WebData (List String))
type alias Model =
{ data : WebData (List String) }
init : ( Model, Cmd Msg )
init =
( { data = NotAsked }, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Response data ->
( { model | data = data }, Cmd.none )
module Child2 exposing (Model, init, updateData)
import WebData exposing (..)
type alias Model =
{ data : WebData (List String) }
init : ( Model, Cmd a )
init =
( { data = NotAsked }, Cmd.none )
updateData : WebData (List String) -> Model -> ( Model, Cmd a )
updateData data model =
( { model | data = data }, Cmd.none )
module Main exposing (..)
import Child1
import Child2
import Html exposing (..)
import Process
import Task
import Time
import WebData exposing (..)
type Msg
= Response (WebData (List String))
| Child1Msg Child1.Msg
type alias Model =
{ data : WebData (List String)
, child1 : Child1.Model
, child2 : Child2.Model
}
init : ( Model, Cmd Msg )
init =
let
( child1, child1Cmd ) =
Child1.init
( child2, child2Cmd ) =
Child2.init
cmd =
-- Simulate latency
Process.sleep (2 * Time.second)
|> Task.andThen (\_ -> Task.succeed [ "foo", "bar" ])
|> Task.perform (\list -> Response (Success list))
in
( { data = NotAsked
, child1 = child1
, child2 = child2
}
, Cmd.batch
[ Cmd.map Child1Msg child1Cmd
, child2Cmd
, cmd
]
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Response data ->
let
( child1, child1Cmd ) =
Child1.update (Child1.Response data) model.child1
( child2, child2Cmd ) =
Child2.updateData data model.child2
in
( { model | data = data, child1 = child1, child2 = child2 }
, Cmd.batch
[ Cmd.map Child1Msg child1Cmd
, child2Cmd
]
)
Child1Msg msg ->
let
( child1, child1Cmd ) =
Child1.update msg model.child1
in
( { model | child1 = child1 }, Cmd.map Child1Msg child1Cmd )
view : Model -> Html Msg
view model =
pre [] [ text <| toString <| model ]
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, view = view
, subscriptions = always Sub.none
}
module WebData exposing (..)
type WebData a
= NotAsked
| Success a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment