0.3.2 • Published 4 years ago

ts-class-autobind v0.3.2

Weekly downloads
20
License
ISC
Repository
github
Last release
4 years ago

Method auto-bind for TypeScript

npm npm version David CircleCI GitHub license npm bundle size (minified + gzip) code style: prettier GitHub top language GitHub code size in bytes GitHub last commit Snyk Vulnerabilities for GitHub Repo TLOC

Based on class-autobind package.

This package provides a single function, autobind, for use within a constructor to bind all methods to the instance itself.

For example, this allows us to pass a method to an event handler element.addEventListener('click', this.onClick) and be sure the onClick method will always be called with the right context.

Note: This has some specific logic for React, but could be used in any project.

Requirements

TypeScript 3.0 or higher

Installation:

npm install --save ts-class-autobind

Usage:

import { autobind } from "ts-class-autobind";

class MyComponent extends React.Component {
    constructor() {
        super(...arguments);
        autobind(this);
    }
    render() {
        return <button onClick={this.onClick}>Click Me</button>;
    }
    onClick() {
        console.log("Button Clicked");
    }
}

Advanced Usage:

If your component will possibly be subclassed (you really should not do this, but some third-party libraries like react-css-modules do so) then you will need to specify which prototype will be the source of methods that are to be automatically bound.

import { autobind } from "ts-class-autobind";

class MyComponent extends React.Component {
    constructor() {
        super(...arguments);
        autobind(this, MyComponent.prototype); // Note the second parameter.
    }
    render() {
        /* ... */
    }
}

class MySubClassedComponent extends MyComponent {
    /* This is probably a very bad idea. */
}

License

This software is BSD Licensed.

0.3.2

4 years ago

0.3.0

5 years ago

0.2.7

6 years ago

0.2.6

6 years ago

0.2.5

6 years ago

0.2.4

6 years ago

0.2.3

6 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.9

6 years ago

0.1.8

6 years ago

0.1.7

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago