When I start a new instance of GameServer, it sets up the socket and listeners as follows.
var GameServer = function() {
this.player = new Player();
var that = this;
// Setup sockets and listeners
var socket = io.listen(8000);
socket.sockets.on('connection', function(client) {
client.on('message', that.onSocketMessage);
client.on('disconnect', that.onSocketDisconnect);
});
}
I then have two prototypes GameServer.prototype.onSocketMessage & onSocketDisconnect.
I have two problems with the current code:
-
Using that = this and the closure? function. Looks ugly.
-
When onSocketMessage is called, the idea is it works out what the message is then calls another function within GameServer. Only this isn’t possible as now this belongs to the socket.io system. See below:
…
function onSocketMessage() {
this.player.move();
}
this.player is no longer available as this. is no longer part of GameServer.
Should my socket setup and message passing be handled outside of GameServer function and prototypes?
Or how else could I resolve this?
Cheers
EDIT
Ok so I have tried this and it works but looks pretty ugly I think:
var socket = io.listen(8000);
socket.sockets.on('connection', function(client) {
client.on('message', function (data) {
that.onSocketMessage(this, that, data);
});
client.on('disconnect', function() {
that.onSocketDisconnect(this, that);
});
});
Can it be improved upon?
Two things that may help. Thing the first:
You can modify a function’s vision of
thisusing thebindmethod.Notice the call to
bind(this)at the end of the function; this instructs JavaScript to create a closure for you, making whateverthisis outside the function,thisinside the function. (If you wanted to makethisinside the function, say,MySomething, you could just as easily callbind(MySomething), thoughbind(this)is the most common use).Thing the second:
You can store data in a Socket.IO socket. So, for example, if one socket is always associated with a player, you can do
The
getandsetmethods take callbacks because the Socket.IO data store can be set to something other than an in-memory store; for example, Redis.