andreypopp / autobind-decorator

Decorator to automatically bind methods to class instances
MIT License
1.45k stars 66 forks source link

No longer works with TypeScript 2.4 #59

Closed viridia closed 5 years ago

viridia commented 7 years ago

TypeScript recently changed how decorators work (it's actually simpler), but autobind-decorator no longer works.

Here's an implementation that works under 2.4 (written in TypeScript) (only works for methods since that's all I use):

export default function autobind(target: any, key: string, descriptor: any): any {
  let fn = descriptor.value;
  let definingProperty = false;
  return {
    configurable: true,
    get() {
      if (definingProperty || this === target.prototype || this.hasOwnProperty(key)
        || typeof fn !== 'function') {
        return fn;
      }
      const boundFn = fn.bind(this);
      definingProperty = true;
      Object.defineProperty(this, key, {
        configurable: true,
        get() {
          return boundFn;
        },
        set(value) {
          fn = value;
          delete this[key];
        },
      });
      definingProperty = false;
      return boundFn;
    },
    set(value: any) {
      fn = value;
    },
  };
}
viridia commented 7 years ago

BTW I've switched over to using bind-decorator for my TypeScript projects, which has similar functionality but supports more recent versions of TypeScript. I still use autobind-decorator for my JS projects.

stevemao commented 7 years ago

@viridia PR welcome

toolness commented 6 years ago

I think this may have been fixed? I just started using this decorator with TypeScript 2.9.2 and it seems to work fine... anyways, thanks for making this @andreypopp, it's very helpful!

stevemao commented 6 years ago

@toolness did you see https://github.com/andreypopp/autobind-decorator/pull/57?

stevemao commented 5 years ago

Any updates on this?

stevemao commented 5 years ago

I think this may have been fixed? I just started using this decorator with TypeScript 2.9.2 and it seems to work fine... anyways, thanks for making this @andreypopp, it's very helpful!

Seems its not a problem anymore. reopen if it still is.