Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created November 26, 2016 15:51
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 simonh1000/9368f9dbd7f93646207ec27fdf3662a2 to your computer and use it in GitHub Desktop.
Save simonh1000/9368f9dbd7f93646207ec27fdf3662a2 to your computer and use it in GitHub Desktop.
Elm Navigation with HTML5 links
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Navigation
import Json.Decode as Json
main =
Navigation.program UrlChange
{ init = init
, view = view
, update = update
, subscriptions = (\_ -> Sub.none)
}
-- MODEL
type alias Model =
{ history : List Navigation.Location
}
init : Navigation.Location -> ( Model, Cmd Msg )
init location =
( Model [ location ]
, Cmd.none
)
-- UPDATE
type Msg
= UrlChange Navigation.Location
| NoOp String
{- We are just storing the location in our history in this example, but
normally, you would use a package like evancz/url-parser to parse the path
or hash into nicely structured Elm values.
<http://package.elm-lang.org/packages/evancz/url-parser/latest>
-}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UrlChange location ->
( { model | history = location :: model.history }
, Cmd.none
)
NoOp _ ->
model ! []
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text "Pages" ]
, ul [] (List.map viewLink [ "bears", "cats", "dogs", "elephants", "fish" ])
, h1 [] [ text "History" ]
, ul [] (List.map viewLocation model.history)
]
viewLink : String -> Html Msg
viewLink name =
li []
[ a
[ href ("/" ++ name)
, stopPropagation
]
[ text name ]
]
stopPropagation =
onWithOptions "click"
{ stopPropagation = False
, preventDefault = True
}
(Json.map NoOp <| Json.succeed "")
viewLocation : Navigation.Location -> Html msg
viewLocation location =
li [] [ text (location.pathname ++ location.hash) ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment