I'm looking for an elegant way to declare identical getter/setters for multiple properties in ES6 classes.
Rather than having a slew of:
set prop_1(value){
this.prop_1 = value;
console.log(`set prop_1 = ${value} and calling updateroom`);
db.updateRoom(this, 'prop_1');
}
...
set prop_n(value){
this.prop_n = value;
console.log(`set prop1 = ${value} and calling updateroom`);
db.updateRoom(this, 'prop_n');
}
I'd like to do something a little more maintainable like this in the class definition adjacent to the other getters and setters:
['prop_1', 'prop_2' ... 'prop_n'].forEach(prop => {
set [prop](value) {
this[prop] = value;
console.log(`set ${prop} = ${value} and calling updateroom`);
db.updateRoom(this, prop);
}
});
But of course can't do that inside the class definition as literals aren't one of the things syntactically allowed there.
Can't even add the setters to the class definition after declaration later via e.g.:
class Room {
// stuff
}
['initialised', 'type', 'owner'].forEach(prop => {
Object.defineProperty(Room, prop, {
set: function(value) {
this[prop] = value;
console.log(`set ${prop} = ${value} and calling updateroom`)
db.updateRoom(this, prop);
}
})
as there is no instance at that point.
So end up going down an arcane path of decorating the constructor, which just means anyone trying to figure out what the heck I was trying to achieve afterwards ends up with a half hour headache and way more complexity.
Am I missing something, has anyone figured out an elegant way of coding this efficiently without repetition of the getter-setters?