JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 87960
  • Score
    100M100P100Q159249F
  • License MIT

The fastest automatic method.bind(this) decorator

Package Exports

  • bind-decorator

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (bind-decorator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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 decorators 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

NPM

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(); // warns 'bind'.
test(); // warns 'bind'.
Test.test(); // logs 'static'.

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(); // warns 'bind'.
test(); // warns 'bind'.
Test.test(); // logs 'static'.