Reputation: 178
When you look at this excerpt of "An Elm introduction":
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
The model
parameter passed to the function subscriptions
must correspond to the current model of the app, i.e. if the model has changed in less that 1 second, the argument model
passed to the function subscriptions
must have taken into account this modification.
As in JS, there are 3 different ways to make a variable calculated in one function update msg model
visible in another subscriptions model
:
But only 2 if you have async code as in the function subscriptions
to keep your model 'sync':
1- make it a global variable, then by reassignment, update the value of the current model:
function app() {
const currentModel = initModel
function update(msg, model) {
const newModel = doSomething(msg, model)
// REASSIGNMENT
currentModel = newModel
}
function subscriptions() {
doSomethingEveryOneSecond(currentModel)
}
}
2- make it an object property
function app() {
const model = initModel
function update(msg, model) {
// MUTATION
model.value = doSomething(msg, model)
}
// model ALWAYS represents the current model
function subscriptions(model) {
doSomethingEveryOneSecond(model)
}
}
My question is how does it work “under the hood” in The Elm Architecture to keep the model sync between the update
and the subscriptions
functions?
Thanks a LOT!
Upvotes: 2
Views: 277
Reputation: 10190
This is part of the what I like about elm and how it steps around the fact that a pure function can't have side effects.
An elm program to run in a browser defines a main something like:
main =
Browser.document { init = init, update = update, view = view, subscriptions = subscriptions }
Nowhere in one's own code does one make a call to any of the functions you pass as parameters in the above, that is all handled by the generated code.
So yes, however you want to think about it, there is somewhere a representation of the current state of the "model" that is being maintained for you and its this that is passed to the update function to generate the next version of the of the model and to the view function to generate a view and so on. Which means that you write pure functions and something else manages the side-effects.
For the most part you shouldn't worry about this (about the implementation) - that's the responsibility of the framework and the if it changes it won't matter so long as the behaviour remains consistent. That said, the generated code (javascript) is there to read if you want to explore more.
Upvotes: 1