首页 > 解决方案 > 在 NodeJS(自定义类)中与 EventEmitter 作斗争;用作类 Connection 扩展 EventEmitter,其中 EventEmitter 是 require('events')

问题描述

自定义类中的自定义事件问题

'ready'一旦类(Connection)“准备好” ,我希望有一个可以发出的事件。

代码

(我已经修剪了类中的大部分代码以使其更容易):

//Connection.js
const fetch = require('node-fetch');
const EventEmitter = require('events');

class Connection extends EventEmitter {
    /**
     * Instansiates the Connection between the REPLIT Database
     * @param connection {String} Connection string URL
     */
    constructor(connection, options) {
        super();
        if (connection) {
            this.connection = connection;
        } else {
            if (!process.env.REPLIT_DB_URL) throw new Error("Please set an env variable REPLIT_DB_URL as the repl's DB URL");
            this.connection = process.env.REPLIT_DB_URL;
        };
        this.emit('ready', connection);
    };
};

代码(我使用的地方.on()

const Connection = require('./Connection.js');

const x = new Connection();
x.on('ready', x2 => console.log(x2))

错误

TypeError: x.on(...) is not a function
    at /home/runner/repldb/index.js:11:1

(指向我使用的地方.on()

我已经做了很多研究,但我仍然很困惑,任何帮助将不胜感激:D

标签: javascriptnode.js

解决方案


推荐阅读