I've looked all around for someone having a similar problem to me and can't find anything. Basically I am creating a real time multiplayer game with NodeJS, Socket.IO, Express, and Jade.
Everything so far is working great, but this is looking to be a relatively large game, and so I've decided to use OOP concepts for it, but I can't figure out how to tie that in with Socket.IO.
Let's say for example I have my main server file, we'll call this server.js:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 4040;
server.listen(port, function() {
console.log('Server listening on port %d', port);
});
app.set('views', __dirname + '/client');
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
//Have a custom routing setup, works fine.
app.get('/', routes.index);
//The /client refers to where the views and css and everything is located
app.use(express.static(__dirname + '/client'));
io.on('connection', function (socket) {
socket.on ...
}
Now that all works fine, but let's say I introduce a player class, we'll call player.js:
var name = '';
function player (name) {
this.name = name;
};
player.prototype.getName = function () {
return this.name;
};
module.exports = player;
Then import that to the server.js class like so:
var player = require('./player.js');
Everything is still working fine to here. I can create new player objects and call their functions.
Where I'm stuck is using Socket.IO outside of the main server.js file.
As far as I can tell, all of my socket.on or socket.emit calls need to be within the io.on('connection') because that's where the socket is created.
The only thing I've seen close to this is using socket.io namespaces, which doesn't really seem to solve my problem because things still have to be in their own io.on('connection').
I've seen socketio-emitter as well, but I certainly will need to listen for socket.on calls and not just emit things.
It seems like there should be a way to use this in a more global scope.