Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using addEventHandler with class methods #40

Open
websharik opened this issue Aug 12, 2021 · 2 comments
Open

Using addEventHandler with class methods #40

websharik opened this issue Aug 12, 2021 · 2 comments
Labels
enhancement New feature or request

Comments

@websharik
Copy link

websharik commented Aug 12, 2021

Simple give class method to addEventHandler not working:

addEventHandler('onClientKey', root, this.blowOnSpace)

"Unable to convert function with a 'this' parameter to function 'handlerFunction' with no 'this'. To fix, wrap in an arrow function, or declare with 'this: void'."

If use 'this: void' - blowOnSpace lost 'this', so bad variant.
If use arrow function - its works:

addEventHandler('onClientKey', root, (...args: any) => { return this.blowOnSpace(...args) })

But have 2 problems:

  1. So lot code
  2. removeEventHandler require callback address

To save original callback address, callback must be save separate:

this.temp['somename'] = (...args: any) => { return this.blowOnSpace(...args) }
addEventHandler('onClientKey', root, this.temp['somename'])
//and then we can
removeEventHandler('onClientKey', root, this.temp['somename'])

So much code for simple operation...

I try make 'cahing method'

methodCache(callback: (...args: any) => void) {
   let name = `${callback}`
   if (!this.temp[name]) {
       /** @noSelf */
       this.temp[name] = (...args: any) => {
           return callback.bind(this)(...args)
       }
   }
   return this.temp[name]
}

and now its looks:

addEventHandler('onClientKey', root, this.methodCache(this.blowOnSpace))
removeEventHandler('onClientKey', root, this.methodCache(this.blowOnSpace))

But now i want methodCache per class... mb any idea to make it more simple ?

@websharik websharik added the enhancement New feature or request label Aug 12, 2021
@Toliak
Copy link
Member

Toliak commented Aug 12, 2021

Hmmm.. error about this looks expected

How would you resolve this.method, if you wrote code on pure Lua? 🤔

UPD: have you tried

const self = this;
addEventHandler('smth', root, function (...args){ 
  self.method(...args);
});

@websharik
Copy link
Author

websharik commented Aug 12, 2021

@Toliak Problem is more deep and just wraping call in function - resolving only once addEventHandler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants