See the full implementation with the suggestions of the accepted answer here: https://github.com/afcastano/elm-nested-component-communication
=================================================================
I have one parent component with two children. See working example
With the Elm Architecture, how can I update the right child when any of the counters in the left child change?
At the moment, I have the parent component reading the nested property of the left child model and setting it to the right child model, but it seems to me that the parent shouldn't know that much about the internal structure of the children.
These are the models and msgs:
type alias MainModel =
{ counterPair : CounterPair
, totals: Totals
}
type alias CounterPair =
{
greenCounter : Counter
, redCounter : Counter
}
type alias Counter =
{
value : Int
, totalClicks : Int
}
type alias Totals =
{
totalRed : Int
, totalGreen : Int
, combinedTotal : Int
}
type MainMsg
= UpdateCounterPair CounterPairMsg
| UpdateTotals TotalsMsg
type alias RedVal = Int
type alias GreenVal = Int
type TotalsMsg
= UpdateTotals RedVal GreenVal
As you can see, the Main model contains two sub models. The pair model in turn, also contains two counter models.
The Total model is interested in changes on the CounterModels of the Pair component.
To do that, the Main update function would be like this:
updateMain: MainMsg -> MainModel -> MainModel
updateMain msg model =
case msg of
UpdateCounterPair counterPairMsg ->
let
counterPairModel = updateCounterPair counterPairMsg model.counterPair
totalsModel = updateTotals (UpdateTotals counterPair.redCounter.value counterPair.greenCounter.value) model.totals
in
{model | counterPair = counterPairModel, totals = totalsModel}
The things that I don't like are in this line:
updateTotals (UpdateTotals counterPair.redCounter.value counterPair.greenCounter.value) model.totals
1 - The Main module needs to know how to get the value of the counters so that it can pass the update to the updateTotal
function.
2 - The Main module also needs to know about the internals of the union type of the Totals module so that it can use UpdateTotals
constructor.
Is there any other way in which Totals component can subscribe to Pair component without the parent knowing the details of the model structure?
Thank you very much.