Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ECMAscript 6: watch changes to class properties

Let's say I have a class defined as follows:

class MyClass {

    constructor (a) {
        this.a = a;     
    }

    _onPropertyChanged() {
        // do something
    }
}

Whenever the property "a" of an instance of MyClass changes, I want to trigger the _onPropertyChanged method on that instance. What is the best (most performant) way to achieve this using ECMAscript 6?

like image 538
revy Avatar asked Apr 17 '17 23:04

revy


People also ask

Can JavaScript classes have properties?

Classes create objects through the new operator. Each object has some properties (data or method) added by the class. The class stores some properties (data or method) itself, which are usually used to interact with instances.

What are ES6 classes?

There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.


2 Answers

There's no 'best' way, and the actual approach always depends on the final goal.

In its simplistic (and performant enough) form it is:

class MyClass {

    constructor (a) {
      this.a = a;     
    }

    get a() {
      return this._a;
    }

    set a(val) {
      this._a = val;
      this._onPropertyChanged('a', val);
    }

    _onPropertyChanged(propName, val) {
        // do something
    }
}
like image 192
Estus Flask Avatar answered Sep 30 '22 11:09

Estus Flask


This is a simple example of what you can do for this situation and for a single property.

class MyClass {

constructor (a) {
    this._a = a;
}

set a(value) {
    let hasChanged = (this._a !== value);
    this._a = value;
    //Assumes value is primitive. Customize for objects
    if(hasChanged) this._onPropertyChanged();

}

_onPropertyChanged() {
    // do something
}
}
like image 21
santon Avatar answered Sep 30 '22 10:09

santon