What is bind-decorator?
The bind-decorator npm package provides a simple way to bind class methods to the instance of the class. This is particularly useful in JavaScript and TypeScript when dealing with event handlers or callbacks where the context of 'this' can be lost.
What are bind-decorator's main functionalities?
Method Binding
This feature allows you to bind a class method to the instance of the class using the @bind decorator. This ensures that the method retains the correct 'this' context when called.
class MyClass {
constructor() {
this.value = 42;
}
@bind
printValue() {
console.log(this.value);
}
}
const instance = new MyClass();
const print = instance.printValue;
print(); // Outputs: 42
Other packages similar to bind-decorator
autobind-decorator
The autobind-decorator package provides similar functionality by automatically binding methods to the instance of the class. It is also used as a decorator and serves the same purpose of maintaining the correct 'this' context in methods.
core-decorators
The core-decorators package offers a collection of decorators, including @autobind, which binds methods to the instance of the class. It provides additional decorators for other common patterns, making it a more comprehensive solution.
bind-decorator
The best automatic context method binding decorator
- It will
throw
exceptions if decorating anything other than function
, run this; - Since the implementation follows the latest
decorator
s purposal where compartion betweeen this
and target
can not be trusted, run this if you don't belive me. @bind
will always return
a configurable
, enumerable
get accessor propertyDescriptor
with value of descriptor.value.bind(this)
.
In fact the whole implementation is just 12 lines of code:
export function bind<T extends Function>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void {
if(!descriptor || (typeof descriptor.value !== 'function')) throw new TypeError(`Only functions can be decorated with @bind. <${propertyKey}> is not a function!`);
return {
configurable: true,
get(): T {
return descriptor.value.bind(this);
}
};
}
export default bind;
Install
Usage
In JavaScript
import bind from 'bind-decorator';
class Test {
static what = 'static';
@bind
static test() {
console.log(this.what);
}
constructor(what) {
this.what = what;
}
@bind
test() {
console.warn(this.what);
}
}
const tester = new Test('bind');
const { test } = tester;
tester.test();
test();
Test.test();
In TypeScript
import bind from 'bind-decorator';
class Test {
public static what: string = 'static';
@bind
public static test(): void {
console.log(this.what);
}
public constructor(public what: string) {
this.what = what;
}
@bind
public test(): void {
console.warn(this.what);
}
}
const tester: Test = new Test('bind');
const { test } = tester;
tester.test();
test();
Test.test();