简体   繁体   English

静态属性在nodejs中的多个文件之间不起作用

[英]static properties doesn't work among multiple files in nodejs

I'm creating a new application using nodejs and socket.io for real time operations, the problem came when I tried to set a static property to use it among all classes that I have, which is io instance. 我正在使用nodejs和socket.io创建一个用于实时操作的新应用程序,当我尝试设置一个静态属性以在我拥有的所有类(即io实例)中使用它时,问题就来了。 what I am doing right now is that I am assigning the io property when the server start, and when trying to get it from other classes it is returned null. 我现在正在做的是在服务器启动时分配io属性,并在尝试从其他类获取它时返回null。 it's like for each require('./myclass') it returns a new instance of the file. 就像对于每个require('./ myclass')一样,它返回文件的新实例。

here is my class where I setting my io instance inside constructor 这是我的类,在其中我在构造函数中设置io实例

class IO {

    constructor(io) {
        IO.io = io;
        ioService.foo ='asdasd';
        // this.run();
    }




}

calling it when the server start inside index.js: 当服务器在index.js中启动时调用它:

const io = require('socket.io')(server, {serveClient: false});
const IO = require('./services/socket/io');
new IO(io);

calling it from other classes 从其他班级叫它

class Admin {

    send(id, type, data) {
        // console.log('IO.io' , io); // it prints null 
        switch (type) {
            case 'ORDER_CREATED':
                io.emit('message', {
                    type: 'ORDER_CREATED',
                    data: data
                }); // error because io undefined
                break;

        }

    }


}

我在nodejs中使用“全局”解决了我的问题,但对执行方法仍然不满意,并等待一些答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM