我有一个自定义事件处理程序类,其中我有以下内容
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!');
}
}
}
}
我在这里试图做的是将listener.client
设置为客户端经过this.client
,但是有两个问题我要解决
处理程序类
。
this.client
总是返回未定义的.我的听众课是:
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';
}
扩展到这个类,然后尝试调用this.client
返回未定义的,有人知道我能做什么或更改以使它工作吗?
发布于 2022-01-05 15:08:55
您正在将listener.exec
传递给emitter
,这使listener.exec
成为回调。当它执行时,它的this
将不像您所期望的那样工作。为了使this
正确工作,必须绑定回调。
试一试这个
emitter?.on(listener.event, listener.exec.bind(listener));
这样,当exec
运行时,它内部的this
将绑定到listener
,因此访问this.client
将等同于listener.client
。
https://stackoverflow.com/questions/70593671
复制相似问题