I have a custom event handler class where I have the following
public client: NullClient;
public path: string;
constructor(client: NullClient, path: string){
this.client = client;
this.path = path;
}
loadAll() {
for(const type of readdirSync(this.path)) {
for(const file of readdirSync(`${this.path}/${type}`).filter((file) => file.endsWith('.js'))) {
const props = require(`${this.path}/${type}/${file}`).default;
const listener: Listener = new props();
listener.client = this.client;
if(listener instanceof Listener) {
const emitter = this.emitters.get(listener.emitter);
if(!this.isEmitter(emitter)) throw new Error(`INVALID EMITTER!`);
listener.type === 'on' ? emitter?.on(listener.event, listener.exec) : emitter?.once(listener.event, listener.exec);
return listener;
} else {
throw new Error('INVALID TYPE!');
}
}
}
}
What I'm trying to do here is set listener.client as the client passed by this.client but there's 2 issues I'm coming accross
console.log(this.client) in the handler class ALWAYS returns an incomplete ClientUser object, where Client#user is ALWAYS null
Trying to call this.client in any of my events ALWAYS returns undefined.
My listener class is:
import NullClient from '../../lib/NullClient';
export default class Listener {
public emitter: string;
public event: string;
public type?: 'on' | 'once';
public client!: NullClient;
constructor(options: ListenerOptions) {
this.emitter = options.emitter;
this.event = options.event;
this.type = options.type || 'on';
}
exec(...args: any) {
throw new Error('EXEC FUNCTION NOT IMPLEMENTED! Your listener is missing an \'exec\' function');
}
}
interface ListenerOptions {
emitter: string;
event: string;
type?: 'on' | 'once';
}
Extending off of this class then trying to call this.client returns undefined, anyone know what I can do or change to make it work?
You are passing listener.exec to the emitter which makes listener.exec a callback. When it executes, its this will not work as you expect. Callbacks must be bound in order for this to work correctly.
Try this instead
emitter?.on(listener.event, listener.exec.bind(listener));
This way, when exec runs, this inside it will be bound to listener so accessing this.client will be equivalent to listener.client