-1

Multiple >4 (around 10) function with bind this in the constructor. Is there a way to shorten the code?

constructor(props: SignupProps) {
    super(props);
    this._setDirty = this._setDirty.bind(this);
    this._handleUserInput = this._handleUserInput.bind(this);
    this._A = this._A.bind(this);
    this._B = this._B.bind(this);
}

I tried the following but couldn't.

 [this._setDirty, _this.handleUserInput, this._A, this._B].bind(this);
dhilt
  • 18,707
  • 8
  • 70
  • 85
user21
  • 1,261
  • 5
  • 20
  • 41

2 Answers2

1

You need to for-loop the methods and call .bind per each iteration to make your approach work. For example:

const methods = ['_setDirty', '_a', '_b', ...];
methods.forEach(method => this[method] = this[method].bind(this));
dhilt
  • 18,707
  • 8
  • 70
  • 85
1

Methods should be assigned with a loop (another answer already mentions that):

for (const prop of ['_setDirty', /* ... */])
  this[prop] = this[prop].bind(this);

Using arrows instead of prototype methods allows to skip bind but this is the only benefit, bound prototype methods are generally preferable because of their flexibility.

Since React is in use, it's safe to assume that a transpiler is used as well, so the project is not limited to ES6.

Decorators can be conveniently used in ES.Next code to bind methods, e.g. bind-decorator:

import bind from 'bind-decorator';

...
constructor(props: SignupProps) {
    super(props);
}

@bind
_setDirty() {...}
...
Estus Flask
  • 206,104
  • 70
  • 425
  • 565