arhoskins
arhoskins

Reputation: 373

Elm: Use `Address String Action`

The canonical example for getting the value from an input is:

view : Address String -> String -> Html
view address string =
  div []
    [ input
        [ placeholder "Text to reverse"
        , value string
        , on "input" targetValue (Signal.message address)
        , myStyle
        ]
        []
    , div [ myStyle ] [ text (String.reverse string) ]
    ]

I get this. But I want my address to be of type Address String Action (where Action is some other type I define). To my understanding, this would mean the address expects a String followed by a Action type as it's "arguments" (I think of Address as a function, but that might not be correct).

Is it possible to use an address type of Address String Action, and then use it with an input in a similar way? Or am I allowed to do Address String Action in the first place?

Upvotes: 0

Views: 61

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

The example you link to is probably a bit too simplistic in that both the Action and Model are a string. You will seldom run into that.

I've tweaked the example with something that is more canonical to elm in its current form:

main =
  StartApp.start { model = { text = "" }, view = view, update = update }

type Action
  = SetText String

type alias Model =
  { text : String }

update : Action -> Model -> Model
update action model =
  case action of
    SetText text ->
      { model | text = text }

view : Address Action -> Model -> Html
view address model =
  div []
    [ input
        [ placeholder "Text to reverse"
        , value model.text
        , on "input" targetValue (Signal.message address << SetText)
        , myStyle
        ]
        []
    , div [ myStyle ] [ text (String.reverse model.text) ]
    ]

Notice how the Action type is a union type listing all the different ways you can interact with the page. In this example, the only thing you can do is to set the text.

The signature of view is now more explicit. The first argument is the address of a mailbox that deals in type Action, and the second argument contains the current state of the model.

view : Address Action -> Model -> Html

There is no need to go down a path of trying something like Address String Action since now Action encapsulates the setting of the text.

Upvotes: 2

Related Questions