0

I'm trying to make a class with a large number of properties, all of which would trigger emission of an event when the instance was changed, What are some good options without creating a wall of static setters?

class MyClass {
    constructor() {
        this._propertyA = "";
        // 50 similar properties
    }
    set propertyA(val) {
        this._propertyA = val;
        this.emitChangeEvent('myClassObjectChanged');
    }
    // I'm trying to avoid creating 50 setters here
}

Or maybe there is a better approach to that in general?

Edit: the suggested duplicate wouldn't work for me as I'm trying to retrofit observability on properties, basically I can only rewrite the class itself but not the whole other code that references it

Scrandre
  • 141
  • 8
  • 1
    Use a function instead? `setValue(myClassObj, 'property', value)`? – evolutionxbox Mar 09 '21 at 21:09
  • take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy – Isaac Mar 09 '21 at 21:13
  • Maybe in a few months there will be decorators in JS and this can be solved quite elegantly, till then all solutions are either hacky or repetitive – Jonas Wilms Mar 09 '21 at 21:15
  • Both proxy and replacing with functions doesn't allow me to retrofit the observability on the class (if I understand the suggestions correctly), it's just if only I could iterate over the properties and assign the same setter to all of them dynamically – Scrandre Mar 09 '21 at 21:26

0 Answers0