1.0.0 • Published 5 years ago
@xornot/bound v1.0.0
xornot.io bound
Decorator for the auto-bind library.
import {bound} from "@xornot/bound";
@bound class MyClass {
public method() {
// "this" will always be an instance of MyClass.
}
}
You can also pass all options supported by the auto-bind library.
@bound({
include: [/^method.*/],
exclude: [/_unbound$/]
})
class MyClass {
public method_bound() {
// Bound because the method name matches an include RegExp.
}
public method_unbound() {
// NOT bound because the method name matches an exclude RegExp.
}
public foo() {
// NOT bound because the method name does not match an include RegExp.
}
}
As a shortcut, you can also pass "include" strings and regular expressions directly to the decorator.
@bound("foo", /bar/) // is equivalent to: @bound({include: ["foo", /bar/]})
class MyClass {
public foo() {
// Bound because "foo" is in the include list.
}
public bar() {
// Bound beacuse /bar/ is in the include list.
}
public baz() {
// NOT bound because the method name does not match the include list.
}
}
To use the auto-bind React automatic exclusion, use the excludeReact
option.
@bound({excludeReact: true})
class MyComponent extends React.Component {
public render() {
// NOT bound because the excludeReact option causes autoBind.react() to be used.
return null;
}
}
Please note that the binding happens after the constructor is called so methods referenced in the constructor are not yet bound.
@bound class MyClass {
constructor() {
const methodRef = this.method;
// "this" will NOT be an instance of MyClass, because it has not been bound yet.
methodRef();
}
public method() {
}
}
const myClass = new MyClass();
const methodRef = myClass.method;
// "this" WILL be an instance of MyClass, because the constructor has been completed.
methodRef();
1.0.0
5 years ago