Choosing the right Elm SPA architecture

And how this impacts your users and your code

Wouter In t Velt
Jan 25, 2017 · 8 min read
Image for post
Image for post
Choices in navigation

Image for post
Image for post

Choice #1: URLs with or without hashes?

a 
[ href "/movies/rogue-one"
, onClickPreventDefault (UrlChange "/movies/rogue-one")
]
[ text "movie details" ]

---
onClickPreventDefault : msg -> Attribute msg
onClickPreventDefault msg =
onWithOptions
"click"
{ preventDefault = True
, stopPropagation = False
}
(Json.Decode.succeed msg)

Image for post
Image for post

Choice #2: Validate a new route before navigating to it?

Image for post
Image for post

Choice #3: Only <a> links for navigation in your view functions?

Choice# 4: Are you OK with a javascript trick for non <a> elements in your views?

div [ customRef "/movies/maleficent" ] [..]

-- Custom helper function
customRef : String -> Attribute msg
customRef path =
let
javascriptCode =
"history.pushState({},'','" ++ path ++ "');"
in
attribute
"onclick"
javascriptCode

Impact on your code

🔥 The easiest path

a 
[ href somePath
, onClickPreventDefault (UrlChange somePath)
]
[ ... ]

🔥🔥 Navigation with other HTML elements

type Route
= Home
| Movies
| MovieDetail String

-- in view
button [ onClick <| RouteChanged (MovieDetail "species") ] [..]

-- in update
case msg of
RouteChange newRoute ->
( model, Navigation.newUrl <| urlFor newRoute )

UrlChange newLocation ->
let
...
in
(newModel, cmdToFetchData)

🔥🔥🔥 Validation and loading before navigating to new page


Elm shorts

Random examples, patterns, ideas, tutorials and other stuff.

Wouter In t Velt

Written by

Corporate Digital Transformation Manager by day, Developing in Elm by night. Fascinated by UX, FP and readable code.

Elm shorts

Random examples, patterns, ideas, tutorials and other stuff. Mostly short posts, sometimes longer. Things I learned in playing with the beautiful language Elm, with help from its awesome community. Hopefully these posts will help you in learning Elm and improving your skills.

Wouter In t Velt

Written by

Corporate Digital Transformation Manager by day, Developing in Elm by night. Fascinated by UX, FP and readable code.

Elm shorts

Random examples, patterns, ideas, tutorials and other stuff. Mostly short posts, sometimes longer. Things I learned in playing with the beautiful language Elm, with help from its awesome community. Hopefully these posts will help you in learning Elm and improving your skills.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store