0
votes

Server:

var 
io=require('socket.io'),
express=require('express'),
UUID=require('node-uuid'),
path=require('path'),
app = express();

app.configure(function(){
    app.use(express.static(path.join(__dirname,'')));
});

var server = require('http').createServer(app).listen(8080);
sio = io.listen(server);

app.get('/', function(req, res){
    res.sendfile('/index.html', {root:__dirname});
});

sio.sockets.on('connection', function(socket){
    socket.userid = UUID();
    socket.on('message', function(){
        console.log('client just sent something');
        socket.emit('news', { hello: 'world' });
    });
});

Client connects index.html at first, then click a href to gameroom.html. This is gameroom.html:

<html>
<head>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="game.room.js"></script>
    <script type="text/javascript" src="client.js"></script>
</head>
</html>

client.js:

window.onload = function(){
    var game = new game_room();
}

game.room.js:

var game_room = function(){
    this.socket = io.connect();

this.socket.on('connect', function(){
    this.socket.emit('message', 'Hello server');
});
}

When the client connects, it should emit the message and the server writes the log, but I didn't get any log. I tried the code without this.socket.on('connect') in game.room.js, and the client can emit the message and I got the log. Also, if I transfer the code from game.room.js to client.js, i.e. in window.onload I created var socket = io.connect() and socket.on('connect', function() {socket.emit('messsage', 'Hello server')}); it works fine.

Can someone help me out or explain what is happening? Thanks.

1

1 Answers

0
votes

You are loosing context you could try bind:

var game_room = function(){
    this.socket = io.connect();


    this.socket.on('connect', function(){
        this.socket.emit('message', 'Hello server');
    }.bind(this));
}

or you could just set this.socket to some local var:

var game_room = function(){
    var socket = this.socket = io.connect();


    this.socket.on('connect', function(){
        socket.emit('message', 'Hello server');
    });
}