resource-boilerplate icon indicating copy to clipboard operation
resource-boilerplate copied to clipboard

Using addEventHandler with class methods

Open websharik opened this issue 4 years ago • 2 comments
trafficstars

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 avatar Aug 12 '21 12:08 websharik

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);
});

Toliak avatar Aug 12 '21 13:08 Toliak

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

websharik avatar Aug 12 '21 15:08 websharik