0
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 
2
  • if you console.log(game.player2), what methods do you see attached to the object? Commented Jan 16, 2012 at 5:15
  • undefined, and if I log the socket object after that it is as expected. It's like the operation just isn't occurring. Commented Jan 16, 2012 at 5:22

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.