Reputation: 1201
This code is running in my node.js server application:
io.sockets.on('connection', function (socket) {
var c = new Client(socket, Tools.GenerateID());
waitingClients.push(c);
allClients.push(c);
if (waitingClients.length === 2)
{
activeGames.push(new Game([waitingClients.pop(), waitingClients.pop()]));
}
});
function Client(socket, id)
{
this.Socket = socket;
this.ID = id;
this.Player = new Player();
this.Update = function(supply)
{
socket.emit('update', { Actions: this.Player.Actions, Buys: this.Player.Buys, Coins: this.Player.Coins, Hand: this.Player.Hand, Phase: this.Player.Phase, Supply: supply});
}
socket.on('play', function(data) {
console.log(data);
console.log(this.Player);
});
socket.emit('id', id);
}
The part I'm having trouble with is the event handler for the 'play' event. console.log(this.Player)
outputs undefined
. I sorta understand why it's wrong, because 'this' refers to something other than my client object (the socket? the anonymous function?) , but I don't know how to re-arrange the code to handle the 'play' event properly, and have full access to the members of the Client object.
Upvotes: 0
Views: 269
Reputation: 17598
You just need to store this
in some other variable inside Client
.
function Client(socket, id)
{
var self = this;
...
socket.on('play', function(data) {
self.Player.play();
});
Upvotes: 1