Automatically bind class methods to this on first access.
Compatible with TypeScript and Babel.
babel-plugin-transform-decorators-legacy is needed for Babel 6.
npm install @mgjm/autobind
Decorate any class method that should be bound to this:
class Foo {
@autobind
handleClick() {
this.doSomething();
}
}The following is an equivalent (not lazy) class definition:
class Bar {
constructor() {
this.handleClick = this.handleClick.bind();
}
handleClick() {
this.doSomething();
}
}@autobind works lazy and calls bind only once.
-
Compared to
this.handleClick = this.handleClick.bind()in the constructor it only binds the method if it is needed. -
Compared to calling
.bind()every time you need to pass your method (e.g. inrender()of aReact.Component) it stores the bound method for further use. -
Compared to class properties (
handleClick = () => { this.doSomething() }) it does not need to create a new function for every instance.
Inspired by autobind-decorator and core-decorators.