socket.IO服务器中的“简单”范围问题

时间:2013-12-06 21:35:19

标签: javascript node.js scope socket.io

我有一个简单的节点.js socket.IO服务器whcihs正在工作,但我的事件回调中的范围是不正确的。如何从我的client.on处理程序中正确引用'client'?

sockIO.sockets.on('connection', function (client){
  // new client is here!
  console.log('A new user connected!');

  //This WORKS!
   client.emit('news', { msg: 'new user connected from socket server' });

  client.on('customEvent', function (data) {
    console.log('I received a custom event and data = ', data);
     //following doesn't get called also 'client.emit' doesn't work
     this.emit('foo', { msg: 'foo from socket server' });
   });

客户端代码

<html>
<p id="text">socket.io</p>


<script src="socket.io/socket.io.js"></script>
<script type="text/javascript" src="js/lib/jquery-1.4.2.min.js"></script>

<script>
    $(document).ready(function(){
        var socket = io.connect('http://localhost');
                text        = $('#text');
console.log('socket is '+socket);
               socket.on('connect', function () {
             $('#text').html('connected');
        });


         socket.on('news', function (info) {
            $('#text').html(info.msg);

        });
          socket.on('foo', function (info) {
            alert('YES foo received from server');
            $('#text').html(info.msg);

        });

        socket.on('disconnect', function () {
             $('#text').html('disconnected');
        });

    });
</script>

1 个答案:

答案 0 :(得分:0)

如果您使用以下代码:

sockIO.sockets.on('connection', function (client) {
    // new client is here!
    console.log('A new user connected!');
    //This WORKS!
    client.emit('news', { msg: 'new user connected from socket server' });
    client.on('customEvent', function (data) {
        console.log('I received a custom event and data = ', data);
        //following doesn't work also 'client.emit' doesn't work
        client.emit('foo', { msg: 'foo from socket server' });
    });
});

没有理由不通过套接字发送foo事件。 customEvent的处理程序没有定义client变量,因此它在父作用域中查找并在那里找到它。如果news事件有效,则foo也应该有效。我建议在客户端检查foo的捕获情况。你真的在听这样的消息吗?