Struggling with Context in Elm Architecture

255 views
Skip to first unread message

Adam Waselnuk

unread,
Feb 11, 2016, 10:01:33 PM2/11/16
to Elm Discuss
I am having a hard time wrapping my head around Context as used in the Elm architecture example 4. Consider the following code:
forwardTo: Address b -> (a -> b) -> Address a

-- Encounter.elm
viewCharacter : Signal.Address Action -> (ID, Character.Model) -> Html
viewCharacter address (id, model) =
  let
    context = 
      Character.Context
        (Signal.forwardTo address (ModifyCharacter id))
        (Signal.forwardTo address (always (RemoveCharacter id)))
  in
    Character.view context model

-- Character.elm
type alias Context =
  { actions : Signal.Address Action
  , remove : Signal.Address ()
  }

view : Context -> Model -> Html
view context character =
  div
    [ class "character" ]
    [
      input
        [
          class "character-level"
        , type' "number"
        , value (toString character.level)
        , on "input" targetValue (\level -> Signal.message context.actions (ModifyLevel (safeStrToLevel level)))
        ] []
    , input
        [
          class "character-name"
        , type' "text"
        , value (character.name)
        , on "input" targetValue (\name -> Signal.message context.actions (ModifyName name))
        ] []
    , button
        [ onClick context.remove () ]
        [ text "Remove" ]
    ]


What is going on with the Context type alias? In my Encounter module I define a context and pass it two Signal Addresses (I think) but in the Character model it is defined as a record. This is really tripping me up. I don't understand how the type is resolving properly or why my Character view gains access to a context record. Can anyone clarify this or point me to some documentation that explains in more detail what is happening?

Max Goldstein

unread,
Feb 11, 2016, 10:29:59 PM2/11/16
to Elm Discuss
I define a context and pass it two Signal Addresses (I think) but in the Character model it is defined as a record.
 
Type aliasing a record defines a record constructor function, which takes the fields of the record in order. So you're calling it as a function that creates a record of that type.

Adam Waselnuk

unread,
Feb 12, 2016, 9:26:08 AM2/12/16
to Elm Discuss
Thank you so much Max that 100% clarifies it! Do you know where I might find documentation on that? 

Max Goldstein

unread,
Feb 12, 2016, 9:33:38 AM2/12/16
to Elm Discuss
Unfortunately the official docs aren't the best. I'll refer you to this page (...which I wrote...).
Reply all
Reply to author
Forward
0 new messages