Reputation: 485
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
Upvotes: 0
Views: 203
Reputation: 18205
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.
'hello'.foo = 'world';
console.log('hello'.foo); // undefined
var str = 'hello';
str.foo = 'world';
console.log(str.foo); // undefined
What you probably meant to do was
for (var key in games)
var game = games[key];
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
Upvotes: 1