Skip to content
This repository has been archived by the owner on May 25, 2023. It is now read-only.
/ autobind Public archive

Decorator for lazy binding of methods.

License

Notifications You must be signed in to change notification settings

mgjm/autobind

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@mgjm/autobind

Automatically bind class methods to this on first access.

Compatible with TypeScript and Babel.

babel-plugin-transform-decorators-legacy is needed for Babel 6.

Install

npm install @mgjm/autobind

Usage

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();
    }
}

Why?

@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. in render() of a React.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.

Credits

Inspired by autobind-decorator and core-decorators.

About

Decorator for lazy binding of methods.

Resources

License

Stars

Watchers

Forks

Packages

No packages published