Reputation: 14418
I'm developing a dynamic form, where the defined cells can either:
I need a way to provide a hint to the user, highlighting the cells he/she must fill to have a valid form.
In other works I could have
cellA -> input by user cellB -> input by user cellC -> formula = cellA + cellB cellA and cellB are required (highlighted). This case is pretty easy to handle.
I can also have more complex formulas, call them scripts. For example
cellC =
if(cellD == true)
{
cellC = cellA;
}
else
{
cellC = cellB;
}
I'm wondering if in javascript it would be possible to understand whether the vars cellA and cellB have been used as a right part in any assignment.
Upvotes: 0
Views: 268
Reputation: 4628
You could achieve something like this but you'd need to use an object (as @T.J Crowder
did in his answer) or by using a Proxy like this
const grid = new Proxy({
cellA: 'CELL-A',
cellB: 'CELL-B',
cellC: 'CELL-C',
cellD: 'CELL-D'
}, {
get (obj, prop) {
if (prop in obj) {
// here you can use an object or whatever you need
// to keep track of used properties/values
console.log(`${prop} has been retrieved.`)
return obj[prop]
}
},
set (obj, prop, val) {
console.log(`${prop} has been set with value ${val}.`)
obj[prop] = val
}
})
Therefore doing
grid.cellA = grid.cellB
Yields
// cellB has been retrieved.
// cellA has been set with value CELL-B.
And sets the correct value of cellB
to cellA
Upvotes: 1
Reputation: 1075337
I'm wondering if in javascript it would be possible to understand whether the vars cellA and cellB have been used as a right part in any assignment.
No, you can't hook into a variable being read like that.
You could make them accessor properties of an object, though, which would give you a means of doing that:
const used = { a: false, b: false, c: false};
const values = { };
const cells = {
get a() {
used.a = true;
return values.a;
},
set a(value) {
values.a = value;
},
get b() {
used.b = true;
return values.b;
},
set b(value) {
values.b = value;
},
get c() {
used.c = true;
return values.c;
},
set c(value) {
values.c = value;
}
};
// You'd only give `cells` to the code doing this, so it doesn' thave
// access to `used` or `values`.
cells.a = 2;
cells.b = 21;
const result = cells.a * cells.b;
console.log("result: " + result);
console.log("a used? " + used.a);
console.log("b used? " + used.b);
console.log("c used? " + used.c);
Alternatively, you could do something similar with a Proxy.
Or you can store the flags and values on the object itself if you're not worried about them being accessible by other code. (Or use a class instance and private fields, which are being implemented in JavaScript engines now...)
Upvotes: 5