resource-boilerplate
resource-boilerplate copied to clipboard
Using addEventHandler with class methods
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:
- So lot code
- 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 ?
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 Problem is more deep and just wraping call in function - resolving only once addEventHandler.