The set accessor does not take place whenever one does mutate the Crumbs class property value by e.g pushing into it.
I'm trying to create a class property via set syntax which I expect to handle an additional sessionStorage task. But every time, I'm going to push an item into the array, the set accessor does not take place.
The code I came up with so far is as follows ...
class Environment {
constructor() {
this.Crumbs = [];
}
set Crumbs(value) {
// debugger;
sessionStorage.setItem('_crumbs', JSON.stringify(value));
}
get Crumbs() {
// debugger;
let result = [];
if (sessionStorage.getItem('_crumbs') !== null) {
result = JSON.parse(sessionStorage.getItem('_crumbs'));
} else {
sessionStorage.setItem('_crumbs', JSON.stringify([]));
}
return result;
}
}
let env = new Environment();
let _metricId = 6;
let _concept = 'Back orders';
let _crumb = {
MetricId: _metricId,
Concept: _concept,
};
env.Crumbs.push(_crumb);
None of the mutating array methods will ever activate the OP's setter. This only happens for direct assignments to
Crumbs.But since the OP wants to go with the least effort of handling array changes by any array operation, the OP needs to expose a proxyfied array as an
Environmentinstance'scrumbsproperty. The proxy'shandlerconfiguration has to implement just thesettrap, and moreover needs to specifically handle just the change to the proxy'slengthproperty, where one would keep the storedcrumbsvalue up to date by storing the local/internalcrumbListmirror.