io.sockets.on('connection', function (socket) {
socket.on('requestGame', function (data) {
for (var game in games)
if (game.player2 === undefined) {
game.player2 = socket;
socket.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // works
game.player2.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // doesn't work
Why does one of these lines work while the other doesn’t?
here is the error
game.player2.emit('gameStart', { game_id: game.game_id, turn: !game.p1_tur
^
TypeError: Cannot call method 'emit' of undefined
The
for (var a in b)syntax iterates through b’s keys. Each time through the loop, a will be a string, and not the value of b that you were probably looking for.Because it’s a string and a literal, attaching a property to it will immediately not have any effect on it. You cannot change literals like strings and numbers in Javascript.
What you probably meant to do was