fiddle icon indicating copy to clipboard operation
fiddle copied to clipboard

Use Typescript Decorators for binding this to class Methods.

Open akgupta0777 opened this issue 3 years ago • 3 comments

Currently in a lot of files, Class Methods are defined and binded with this keyword so that the correct object gets referenced on calling. An example of this - https://github.com/electron/fiddle/blob/50b6656690801882a9fc907669de3002199e4d9b/src/renderer/bisect.ts#L9-L12

Since project is written in TypeScript we can use typescript experimental decorators on class Methods that will automatically bind this keyword to the functions attached with the decorator.

This is a great improvement in code quality and also we can reduce a lot of lines of code.

akgupta0777 avatar Mar 29 '22 17:03 akgupta0777

Hey. I'd like to take this up if this has not already been solved or if you guys have still not moved into functional component. I propose we write a decorator function like this

const bind = (context) => {
  return (target, memberName, propertyDescriptor) => {
    get() {
      const boundedFunction = propertyDescriptor.value.bind(context)
      Object.defineProperty(context, memberName, {
        value: boundedFunction
      })
      return boundedFunction
    }
  }
}

Do let me know if this is the right way and would be happy to contribute

punndcoder28 avatar Jun 17 '22 10:06 punndcoder28