【问题标题】:'simple' scoping issue in socket.IO serversocket.IO 服务器中的“简单”范围问题
【发布时间】:2013-12-06 21:35:18
【问题描述】:

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

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>

【问题讨论】:

  • 你说它不起作用是什么意思?抛出异常还是无法解决?
  • 永远不会被调用,否则无法调用未定义的方法'emit'

标签: javascript node.js scope socket.io


【解决方案1】:

如果你使用以下代码:

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 的捕获情况。你真的在听这样的消息吗?

【讨论】:

  • 但是您真的在客户端监听foo 事件吗?你能发布一些客户端的js代码吗?
  • 如果我从处理程序中跟踪 typeof(client.emit) ,它会正确跟踪函数...WTF??
  • 好的,现在我看到了你的客户端代码,但是我没有看到customEvent 的调用。这意味着您的代码永远不会进入后端代码中的customEvent 处理程序,并且永远不会调用client.emit('foo')
猜你喜欢
  • 2021-06-19
  • 1970-01-01
  • 2011-03-17
  • 2010-10-21
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
相关资源
最近更新 更多