2

I have a Module

var exports = module.exports = {};

exports.refresh = function (msg) {
    socket.emit('refresh', { message: msg });
}

exports.lock = function (msg) {
    socket.emit('lock', { message: msg });
}

and in my server.js I defined

var io = require("socket.io").listen(server);

and call the module

var period = require('./server/functions/period.js');

How can I pass Socket to the Module (period.js) so that I have access on the socket methods, for example socket.emit, broadcast and io.sockets.emit.

1 Answer 1

1

There are a few ways to solve this. It depends on how you want to use the actual module. Only one instance for every socket, or one for each socket. I suggest you make your module return a constructor instead of an object literal, like below:

module.exports = function(socket) {
    var socket = socket;

    this.refresh = function (msg) {
        socket.emit('refresh', { message: msg });
    }

    this.lock = function (msg) {
        socket.emit('lock', { message: msg });
    }

}

Then you can create new objects containing the actual socket.

var Period = require('./server/functions/period.js'),
    period = new Period(socket);

One solution would probably be to do this with every connecting socket.

var periodModule = require('./server/functions/period.js'),

io.on('connection', function(socket){
    var period = new periodModule(socket);

    //make a call
    period.refresh();
});

You could also pass the io object in to your module to get the broadcasting interface as well.

 module.exports = function(socket, io) {
    var socket = socket,
        io = io;

    this.broadcastSomething = function(..) {
        io.emit('data', { data: 'data'});
    }

    this.refresh = function (msg) {
        socket.emit('refresh', { message: msg });
    }

    this.lock = function (msg) {
        socket.emit('lock', { message: msg });
    }

}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much! i changed my module in a constructor, but now i get the error when calling period.refresh() that there is no method 'refresh'. Any ideas?
try return this in the module
found the mistake :D I have a Mongo Model with the Name Period :D Sorry
I found another problem, maybe you can help. When I restart the server and the client is connected at this time the server crashes with the error the Object 51 has no method refresh. Any Idea how I can prevent this? And what the reason could be? How is it possible to use one instance for all, when socket is only available in the io.connection function?
I think I have fixed this using {'force new connection': true}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.