This page covers Elm 0.18


Next let's add buttons to navigate between views.

EditPlayer message

Change src/Players/Messages.elm to include two new actions:


type Msg
    = OnFetchAll (Result Http.Error (List Player))
    | ShowPlayers
    | ShowPlayer PlayerId

We added ShowPlayers and ShowPlayer.

Players List

The players' list needs to show a button for each player to trigger the ShowPlayer message.

In src/Players/List.elm. First add Html.Events:

import Html.Events exposing (onClick)

Add a new function for this button at the end:

editBtn : Player -> Html Msg
editBtn player =
        [ class "btn regular"
        , onClick (ShowPlayer
        [ i [ class "fa fa-pencil mr1" ] [], text "Edit" ]

Here we trigger ShowPlayer with the id of the player that we want to edit.

And change playerRow to include this button:

playerRow : Player -> Html Msg
playerRow player =
    tr []
        [ td [] [ text (toString ]
        , td [] [ text ]
        , td [] [ text (toString player.level) ]
        , td []
            [ editBtn player ]

Player Edit

Let's add the navigation button to the edit view. In /src/Players/Edit.elm:

Add one more import:

import Html.Events exposing (onClick)

Add a new function at the end for the list button:

listBtn : Html Msg
listBtn =
        [ class "btn regular"
        , onClick ShowPlayers
        [ i [ class "fa fa-chevron-left mr1" ] [], text "List" ]

Here we send the ShowPlayers when the button is clicked.

And add this button to the list, change the nav function to:

nav : Player -> Html Msg
nav model =
    div [ class "clearfix mb2 white bg-black p1" ]
        [ listBtn ]

Players Update

Finally, src/Players/Update.elm needs to respond to the new messages.

import Navigation

And add two new branches to the case expression:

update : Msg -> List Player -> ( List Player, Cmd Msg )
update message players =
    case message of

        ShowPlayers ->
            ( players, Navigation.newUrl "#players" )

        ShowPlayer id ->
            ( players, Navigation.newUrl ("#players/" ++ id) )

Navigation.newUrl returns a command. When this command is run by Elm the location of the browser will change.

Test it

Go to the list http://localhost:3000/#players. You should now see an Edit button, upon clicking it the location should change to the edit view.

Up to this point your application code should look

results matching ""

    No results matching ""