I have a data model that I am hydrating through a process I control, so I can update its schema and properties if required:
results:
{
pizza: [
{ source: '2', symbol: 'pizza', id: '2.pizza', cost: '0.00' },
{ source: '4', symbol: 'pizza', id: '4.pizza', cost: '0.00' }
],
apple: [
{ source: '3', symbol: 'apple', id: '3.apple', cost: '0.00' },
{ source: '4', symbol: 'apple', id: '4.apple', cost: '0.00' },
{ source: '4', symbol: 'apple', id: '4b.apple', cost: '0.00' }
]
}
For the view, using React, I will want to display this data in a table that will update each result’s totalAmount
, updating the table cell for that row. However, more importantly for now is how to update the model.
Now that we have the initial data model, I need to add event listeners (after we have the model) to each source
object, each with their own unique endpoint to execute a function. I can subscribe to a source
event that fires whenever that source has a change. When there is a change, I want to update that source’s cost
, add all costs for that result
and update that result’s totalAmount
amount but not update any other totalAmounts (but we can, but not as elegant).
First question is how to add an object listener only to each source
object and not update all sources in the model? For this, I have tried the following from here but haven’t gotten it to work on testing, and not sure how I would add something like this to my objects.
var MyVar = {
_prop1: 0,
get prop1() { return this._prop1; },
set prop1(value) { this._prop1 = value; /*Listener code can go here*/ }
};
Secondly, once a change is detected, the callback should do something like results["pizza"].totalAmount = {sum of all costs for this object}
. This would add a totalAmount
property. However would it be better to create an empty property to fill in later?
{ source: '2', symbol: 'pizza', id: '2.pizza', cost: '0.00' },
<== change detected, cost changed to 5.00.
The resulting model for this object would then be:
{
pizza: [
{ source: '2', symbol: 'pizza', id: '2.pizza', cost: '0.00' },
{ source: '4', symbol: 'pizza', id: '4.pizza', cost: '0.00' },
totalAmount: '5.00'
], ...
And the table updated with the new values.