简体   繁体   中英

Socket.io socket handles

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.

'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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM