Search code examples
javascriptreactjsecmascript-next

Use bind operator to curry a function?


Given that this.handler.bind(this) can be replaced with ::this.handler, how can I replace this.handler.bind(this, 1) using ::?

I found this useful in a situation where I want to attach handlers to react components. E.g.:

handler(x) {
  this.setState({counter: x})
}

<a onClick={this.handler.bind(this, 5)}>increment by 5</a>

I know that I can use _.curry (lodash) but it's pretty much the same in terms of code readability:

<a onClick={_.curry(::this.handler, 5)}>increment by 5</a>

Solution

  • The ES next draft for the bind operator does not feature partial application as it is currently specced. Just continue to use bind (this.handler.bind(this, 5) or a simple arrow function e => this.handler(5, e).