Skip to content
Automatically bind methods to their class instance
JavaScript TypeScript
Branch: master
Clone or download
Latest commit 2579065 May 28, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Create funding.yml May 28, 2019
.editorconfig Meta tweaks Jan 19, 2018
.gitattributes Require Node.js 6 Jun 20, 2018
.gitignore Meta tweaks Jan 19, 2018
.npmrc Meta tweaks Jan 19, 2018
.travis.yml Require Node.js 6 Jun 20, 2018
index.d.ts Minor TypeScript definition tweaks May 21, 2019
index.js Correctly bind inherited properties Dec 23, 2018
index.test-d.ts Add TypeScript definition (#15) Apr 7, 2019
license
package.json Minor TypeScript definition tweaks May 21, 2019
readme.md Correctly bind inherited properties Dec 23, 2018
test.js Correctly bind inherited properties Dec 23, 2018

readme.md

auto-bind Build Status

Automatically bind methods to their class instance

It also correctly binds inherited properties.

Install

$ npm install auto-bind

Usage

const autoBind = require('auto-bind');

class Unicorn {
	constructor(name) {
		this.name = name;
		autoBind(this);
	}

	message() {
		return `${this.name} is awesome!`;
	}
}

const unicorn = new Unicorn('Rainbow');

// Grab the method off the class instance
const message = unicorn.message;

// Still bound to the class instance
message();
//=> 'Rainbow is awesome!'

// Without `autoBind(this)`, the above would have resulted in
message();
//=> Error: Cannot read property 'name' of undefined

API

autoBind(self, [options])

Bind methods in self to their class instance. Returns the self object.

self

Type: Object

Object with methods to bind.

options

Type: Object

include

Type: Array<string|RegExp>

Bind only the given methods.

exclude

Type: Array<string|RegExp>

Bind methods except for the given methods.

autoBind.react(self, [options])

Same as autoBind, but excludes the default React component methods.

class Foo extends React.Component {
	constructor(props) {
		super(props);
		autoBind.react(this);
	}

	//
}

Related

  • bind-methods - Bind all methods in an object to itself or a specified context

License

MIT © Sindre Sorhus

You can’t perform that action at this time.