The “game loop” of Elm
This is the backbone of a web application written in the Elm language (https://elm-lang.org/). This loop happens every time something happen. The “something” is converted to a message (Msg) and sent to the update function (the controller) together with the Model. The model contains the entire state of the application (the “single source of true”). The update function, based solely on the model and the message, can change the model and generate one or more commands (Cmd). Commands are then executed by the Elm Runtime while the new model is used to update the application interface, after being processed by the view function. This is in short all you need to know about The Elm Architecture.
Steps
- Something happen (example: user click on a button)
- A message (
Msg
) is generated Msg
+Model
are sent toupdate
update
return a newModel
and an optional command (Cmd
)Cmd
is sent to the effects engine and executed (example: an http request)- The new
Model
is sent to theview
view
return new html- New html is used to update the web page
- Go to step 1
Notes
- The two section in the Unsafe Area (DOM and Effect) are similar in a sense that both are causing side effect and are generating messages. The difference is that DOM change the page based on
Model+view
while Effects generate effect based onCmd
- in Elm 0.19,
view
may return aDocument msg
instead ofHtml msg
, but the concept is the same - Safe Area is the area that doesn’t have side effects. Everything in pure here and is the area where we write our code
- Unsafe Area — in contrast — is where there are side effects. We let Elm handle this dangerous zone
- When I say “
Msg
andModel
are sent to theupdate
”, what I really mean is that the Elm Runtime call theupdate
function with the message and the model as parameter as in:update msg model
- Subscriptions are another thing that can send messages. They are not in the animation, but they behave the same as Effect and DOM. The messages are sent from subscriptions on Javascript events, for example the resizing of the browser, or sending data through a port. The type signature is
subscriptions : model -> Sub msg
- The type signature for the update is
update : msg -> model -> ( model, Cmd msg )
- The type signature for the view is
view : model -> Html msg
For more details on The Elm Architecture have a look at the excellent official guide: https://guide.elm-lang.org/architecture/