38

Javascript classes: state management

 4 years ago
source link: https://medium.com/@tobiasuhlig/javascript-classes-state-management-87d66874ac8a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In case you are working with the ES6+ class system, you most likely want to use configs (properties) for your own classes. Since the class system is still lacking to define these inline, you could use the constructor:

1*UcIQBeLUoPrbg-LiNB6l6A.png?q=20

You will most likely notice right away, that this approach is not really helpful, since you have no change listeners for your class configs. Defining the properties via get & set can help with this:

1*PiOPThrqOX0qEal3aSojkA.png?q=20

Both class definitions are pretty similar, but the 2nd one allows us to use myInstance.a = 2; for automatically triggering the setter. As a design pattern, saving the content of each property inside a underscore prefixed version does make sense (e.g. a => _a). You could add more logic into each setter, but as soon as you want to extend your own classes again, this will cause problems. So calling new methods which you can extend or override makes more sense:

1*KZ9SJCtv2RXlJQKUdKPa8g.png?q=20

Passing the new & the old value makes a lot of sense. As a design pattern, I recommend to use method names like afterSetMyConfig(). In case you want to extend your class now, you can override afterSetA and use the superclass call (super.afterSetA(value, oldValue);) as needed.

In case you are using the neo.mjs framework , you can shorten this code quite a bit:

1*0EEgLDwKtJtVPt2xywkQjw.png?q=20

applyClassConfig will generate something similar to the previous version, with the difference that you can change the default values for your properties more easily when extending classes.

Chicken or egg?

You might have noticed that afterSetA() is using this.b internally. You could flip the order of a_ & b_ inside the getConfig() method to change the order in which the configs do get applied. Since afterSetB() is using this.a internally, we ended up with a circular reference , so we can not solve this issue just using the config order. In neo.mjs, i solved it like this:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK