Skip to content

Instantly share code, notes, and snippets.

@szabba
Created June 18, 2016 23:33
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 szabba/c6e091c9d9d3088656c2e9a5de2e0f72 to your computer and use it in GitHub Desktop.
Save szabba/c6e091c9d9d3088656c2e9a5de2e0f72 to your computer and use it in GitHub Desktop.
import Html as H exposing (Html)
import Html.Events as HE
type alias Model =
{ data : String
, moreData : String
}
init : Model
init =
Model "hakuna" "matata"
type Msg
= NewData String
| MoreNewData String
-- A traditional view looks like this, you use
--
-- Html.App.map : (a -> b) -> Html a -> Html b
--
-- on it's result to "updgrade" the messages inside it to a
-- parent component's message type.
--
-- Use it as
--
-- Html.App.map ChildMsg <| view model.child
view : Model -> Html Msg
view model =
H.div []
[ H.p
[ HE.onClick (NewData "")
]
[ H.text model.data ]
, H.p []
[ H.text model.moreData ]
]
-- This is a view that takes the message-transforming function
-- you'd normally pass to a `Html.App.map` and uses it directly
-- itself. This way the messages embedded in the view can have
-- the type expected by the parent component without
-- `Html.App.map` being called.
--
-- Use it as
--
-- mapFreeView ChildMsg model.child
--
mapFreeView : (Msg -> msg) -> Model -> Html msg
mapFreeView mapMsg model =
H.div []
[ H.p
[ HE.onClick (mapMsg <| NewData "")
]
[ H.text model.data ]
, H.p []
[ H.text model.moreData ]
]
-- This is like `mapFreeView` but it also takes a function that
-- produces a top-level navigation message as it's first argument.
-- In this case both `goTo` and `mapMsg` have to return messages
-- targeted at the root component -- not the immediate parent.
--
-- The use would look something like
--
-- viewWithGoto goTo (mapMsg << ChildMsg) model.child
--
-- where `goTo` and `mapMsg` would be functions passed to the
-- parent's view by earlier ancestors.
--
viewWithGoTo : (String -> msg) -> (Msg -> msg) -> Model -> Html msg
viewWithGoTo goTo mapMsg model =
H.div []
[ H.p
[ HE.onClick (mapMsg <| NewData "")
]
[ H.text model.data ]
, H.p []
[ H.text model.moreData ]
, H.p
[ HE.onClick <| goTo "#someHash" ]
[ H.text "Visit #someHash" ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment