Reputation:
I've got a simple express app and I'd like to have my socket listening info in separate files in a sockets
directory (each file in there would correspond to a controller - separation of concerns).
In app.js
, I'm trying to get this to work:
io.on('connection', function(socket) {
socket.on('game-save-comment', require('./sockets/games.js')(data));
});
And ./sockets/games.js
looks like:
var GameSockets = function(data) {
console.log('got here');
}
exports.GameSockets = GameSockets;
However, I'm getting this error:
socket.on('game-save-comment', require('./sockets/games.js')(data));
^
ReferenceError: data is not defined
What am I missing?
Upvotes: 0
Views: 360
Reputation: 2693
There are two issues here. Since you export GameSockets
as named function, so in app.js
you should use it as:
io.on('connection', function(socket) {
socket.on('game-save-comment', require('./sockets/games.js').GameSockets(data));
});
However the error you are getting is not caused by this. You should pass a function to .on()
event handler, but you try to pass there the result of execution of this funtion. So finally your app.js
should look like (please note absence of function call):
io.on('connection', function(socket) {
socket.on('game-save-comment', require('./sockets/games.js').GameSockets);
});
Upvotes: 1