Skip to content

Instantly share code, notes, and snippets.

@thedumbtechguy
Last active July 9, 2017 18:40
Show Gist options
  • Save thedumbtechguy/b930cfe1f066e24bc266d6b9d1eac059 to your computer and use it in GitHub Desktop.
Save thedumbtechguy/b930cfe1f066e24bc266d6b9d1eac059 to your computer and use it in GitHub Desktop.
Elm Parent Child Communication
module App exposing (Model, initialModel, update, view)
import Html exposing (..)
import Login as Login
type alias Model =
{ loginModel : Login.Model
, pressCount : Int
}
initialModel : Model
initialModel =
{ loginModel = Login.Model "" ""
, pressCount = 0
}
type Msg
= OnLoginPageMsg Login.Msg
| OnLogin
update : Msg -> Model -> Model
update msg model =
case msg of
OnLoginPageMsg msg ->
{ model | loginModel = Login.update msg model.loginModel }
OnLogin ->
{ model | pressCount = model.pressCount + 1 }
view : Model -> Html Msg
view model =
let
page =
Login.view model.loginModel { onInternal = OnLoginPageMsg, onLogin = OnLogin }
in
div []
[ text ("Pressed " ++ toString model.pressCount ++ " times")
, br [] []
, text (model.loginModel.username ++ ":" ++ model.loginModel.password)
, page
]
module Login exposing (Model, Msg, ViewConfig, update, view)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
-- message
type Msg
= Username String
| Password String
-- model
type alias Model =
{ username : String
, password : String
}
-- update
update : Msg -> Model -> Model
update msg model =
case msg of
Username name ->
{ model | username = name }
Password password ->
{ model | password = password }
-- view
type alias ViewConfig msg =
{ onInternal : Msg -> msg
, onLogin : msg
}
view : Model -> ViewConfig msg -> Html msg
view model config =
div []
[ input [ type_ "text", placeholder "Username", onInput (config.onInternal << Username) ] []
, br [] []
, input [ type_ "password", placeholder "Password", onInput (config.onInternal << Password) ] []
, br [] []
, br [] []
, button [ onClick config.onLogin ] [ text "Login" ]
]
module Main exposing (..)
import App
import Html exposing (Html)
import RouteUrl
main =
Html.beginnerProgram
{ model = App.initialModel
, view = App.view
, update = App.update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment