Tengo una clase de controlador de eventos personalizada donde tengo lo siguiente
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!'); } } } } Lo que estoy tratando de hacer aquí es configurar listener.client como el cliente pasó por this.client pero hay 2 problemas con los que me estoy encontrando.
console.log(this.client) en la clase de controlador SIEMPRE devuelve un objeto ClientUser incompleto, donde Client#user SIEMPRE es nulo
Intentar llamar a this.client en cualquiera de mis eventos SIEMPRE devuelve indefinido.
Mi clase de oyente es:
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'; } Extender fuera de esta clase y luego intentar llamar a this.client devuelve indefinido, ¿alguien sabe qué puedo hacer o cambiar para que funcione?
Está pasando listener.exec al emitter , lo que hace que listener.exec sea una devolución de llamada. Cuando se ejecuta, this no funcionará como espera. Las devoluciones de llamada deben vincularse para que this funcione correctamente.
Prueba esto en su lugar
emitter?.on(listener.event, listener.exec.bind(listener)); De esta manera, cuando se ejecute exec , this dentro estará vinculado a listener , por lo que acceder a this.client será equivalente a listener.client