Reputation: 1568
I'm creating a game that allows two socket connections with Node.js and Socket.io. There is a "host" and and "join" function. First the host connects, but I want to make sure they cannot connect again to another game, so I put in a conditional to check if the game object has been created for that socket. For some reason, (with the simplified code I used below), the Game object is not saved with the UserSocket object. I'm assuming it's a scoping issue, but not really sure.
function Game(gameid) {
this.gameID = gameid;
this.joined = false;
this.active = false;
this.baseball = false;
}
function UserSocket(sock) {
o = this;
o.sock = sock;
o.sock.on('clientData', function (data) {
o.CreateGame(data);
});
o.CreateGame = function (hostdata) {
console.log('in create game');
--->console.log(o.game); //*** this call always returns null
if (o.game) {
console.log('game already started'); // this never happens
return false;
}
newgame = new Game(hostdata);
console.log("game object created");
console.log(newgame.gameID);
newgame.host = o.sock;
o.game = newgame;
console.log(o.game);
arrGames.push(newgame);
o.SendToHostSocket("Hosting game: " + newgame.gameID );
}
}
Upvotes: 0
Views: 203
Reputation: 707328
You at least need to change:
function UserSocket(sock) {
o = this;
...
to this:
function UserSocket(sock) {
var o = this;
...
The way you had it, o
was an implicit global variable. If anyone called new UserSocket()
a second time, you would overwrite the value in o
and then your first socket would no longer work properly.
In Javascript all variables that are intended for use only within a function should be preceded with var
upon their first declaration. If you leave that out, then they become "implicit global variables" that are accessible to all your code and subject to inadvertently being overwritten. Implicit global variables are a bad coding practice that often leads to bugs and, in fact, if you run your code in strict mode, this causes an error and the code will not even run.
Upvotes: 1