首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >客户端返回未定义的

客户端返回未定义的
EN

Stack Overflow用户
提问于 2022-01-05 13:27:47
回答 1查看 96关注 0票数 0

我有一个自定义事件处理程序类,其中我有以下内容

代码语言:javascript
运行
复制
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,但是有两个问题我要解决

处理程序类

  1. console.log(this.client)总是返回一个不完整的ClientUser对象,其中Client#user总是 null

  1. 试图在任何事件中调用this.client 总是返回未定义的.

我的听众课是:

代码语言:javascript
运行
复制
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返回未定义的,有人知道我能做什么或更改以使它工作吗?

EN

回答 1

Stack Overflow用户

发布于 2022-01-05 15:08:55

您正在将listener.exec传递给emitter,这使listener.exec成为回调。当它执行时,它的this将不像您所期望的那样工作。为了使this正确工作,必须绑定回调。

试一试这个

代码语言:javascript
运行
复制
emitter?.on(listener.event, listener.exec.bind(listener));

这样,当exec运行时,它内部的this将绑定到listener,因此访问this.client将等同于listener.client

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70593671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档