Omar Shrbaji
Omar Shrbaji

Reputation: 137

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. 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. it's like for each require('./myclass') it returns a new instance of the file.

here is my class where I setting my io instance inside constructor

class IO {

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




}

calling it when the server start inside 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;

        }

    }


}

Upvotes: 0

Views: 205

Answers (1)

Omar Shrbaji
Omar Shrbaji

Reputation: 137

I solved my problem using "global" in nodejs, still Unconvinced with the way I did it, and waiting some answers.

Upvotes: 0

Related Questions