How to pass the reference of a variable (io - Socket.io) to a class in JS [Node.js]?

0

I would like to know what is the correct way to pass the reference of the variable io to a class in Node.js

I currently have the variable initialized in a file index.js :

const io = require('socket.io').listen(9000)

Reading some blogs I have observed that they only pass the variable to the constructor in this way:

class Foo{
    constructor(io){
        this.io = io
    }
}

let objFoo = new Foo(io)

However, if it contains an object with active sockets inside it, the question is: Will the attribute io of the class contain the connections (active sockets) that are made after the instantiation of the same? if not, is there any other way to refer to the variable io from another .js document (since the class is in another doc.)?

    
asked by Roberto Robles Rodriguez 12.05.2017 в 05:30
source

2 answers

0
  

¿El atributo io de la clase contendrá las conexiones (sockets activos) que se hagan posterior a la instanciación de la misma?

Remember that, in Javascript, Objects (data not primitives ) are passed by reference .

That means that, in reality, you're using exactly the same object everywhere. Even if you copy it (as you indicate in your example), in reality you will continue using the same object , although with several different names.

In summary: if , it will contain anything that contains the original object, since it is the same. Even if you add after you copy it.

    
answered by 17.05.2017 / 19:33
source
0

You could make a file where you raise the socket with io and export that variable:

It would be something like this: socket.js

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

module.exports = io

And where you want to use it would be something like: archivo.js

const io = require('./rutaArchivo/socket')
    
answered by 17.05.2017 в 19:12