Avoid making asynchronous calls, API requests or DOM manipulations in the `constructor`.
Move them into separate functions instead. This will make tests easier to write and
code easier to maintain.
```javascript
// bad
classmyClass{
constructor(config){
this.config=config;
axios.get(this.config.endpoint)
}
}
// good
classmyClass{
constructor(config){
this.config=config;
}
makeRequest(){
axios.get(this.config.endpoint)
}
}
constinstance=newmyClass();
instance.makeRequest();
```
## Avoid classes to handle DOM events
If the only purpose of the class is to bind a DOM event and handle the callback, prefer
...
...
@@ -215,7 +186,7 @@
this is no longer necessary after the transition from Sprockets to webpack.
Do not use them anymore and feel free to remove them when refactoring legacy code.
## Global namespace and side effects
## Global namespace
Avoid adding to the global namespace.
...
...
@@ -227,6 +198,10 @@
exportdefaultclassMyClass{/* ... */}
```
## Side effects
### Top-level side effects
Top-level side effects are forbidden in any script which contains `export`:
```javascript
...
...
@@ -238,5 +213,5 @@
}
```
Avoid constructors with side effects whenever possible.
### Avoid side effects in constructors
...
...
@@ -242,4 +217,6 @@
Side effects make constructors difficult to unit test and violate the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle).
Avoid making asynchronous calls, API requests or DOM manipulations in the `constructor`.
Move them into separate functions instead. This will make tests easier to write and
avoids violating the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle).