Chapter 4. The Elm Architecture
Elm programs have a standard architecture which consists of a data
model, a view function that renders that model into HTML, and an update function that handles all updates to the model. You might find this familiar, as it’s a variation of the Model-View-Controller pattern.
The first step in writing an Elm app is to register these components with the Elm runtime. A basic Elm application looks like this:
main =
Html.beginnerProgram
{ view = view
, model = 0
, update = update
}
type Msg
= Increment
| Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
Decrement ->
model - 1
view : Model -> Html Msg
view model = div [ onClick Increment ] [ text (toString model) ]
Notice that it doesn’t matter in which order everything is declared
in our code (in our main definition, we reference our view function
and our update function even though they are defined later in the file). This is because our file isn’t executed from top to bottom, but is
instead a collection of types and functions. Execution is handled
separately by the Elm runtime using the functions that we provide it.
All the data used in an Elm application is described in the data model.
Commonly this is captured as an Elm record, but any type can be used as
the model. In this example, our model is just a number. We
didn’t need to tell the compiler this because it inferred that fact when
we used addition and specified the initial value as 0.
Our update function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access