【问题标题】:socket.io, adding message handler dynamicallysocket.io,动态添加消息处理程序
【发布时间】:2014-03-05 23:25:30
【问题描述】:

我愉快地编写了一个 node.js 服务器,它使用 socket.io 与客户端通信。 这一切都很好。 socket.on('connection'...) 处理程序有点大,这让我想到了另一种方法来组织我的代码并将处理程序添加到生成器函数中,如下所示:

sessionSockets.on('connection', function (err, socket, session) {
  control.generator.apply(socket, [session]);
}

生成器接受一个包含套接字事件及其各自处理函数的对象:

var config = {
  //handler for event 'a'
  a: function(data){
    console.log('a');
  },

  //handler for event 'b'
  b: function(data){
    console.log('b');
  }
};


function generator(session){

  //set up socket.io handlers as per config
  for(var method in config){
    console.log('CONTROL: adding handler for '+method);

    //'this' is the socket, generator is called in this way
    this.on(method, function(data){
      console.log('CONTROL: received '+method);
      config[method].apply(this, data);
    });
  }
};

我希望这会将套接字事件处理程序添加到套接字,确实如此,但是当任何事件进入时,它总是调用最新添加的事件,在这种情况下总是调用 b 函数。

有人知道我在这里做错了什么吗?

【问题讨论】:

  • 你有更多的代码,比如你用来触发事件的代码吗?

标签: javascript node.js socket.io


【解决方案1】:

出现问题是因为到那时this.on 回调触发(假设在绑定它几秒钟后),for 循环结束,method 变量成为最后一个值。

要解决这个问题,您可以使用一些 JavaScript 魔法:

//set up socket.io handlers as per config
var socket = this;
for(var method in config){
  console.log('CONTROL: adding handler for '+method);

  (function(realMethod) {
    socket.on(realMethod, function(data){
      console.log('CONTROL: received '+realMethod);
      config[realMethod].apply(this, data);
    });
  })(method);  //declare function and call it immediately (passing the current method)
}

这种“魔力”初见时难以理解,但当你得到它时,事情就变得清晰了:)

【讨论】:

  • 哇,非常感谢这个快速有效的答案! (除了一点错别字,倒数第二行应该有 } 而不是 ] :)
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2014-07-06
相关资源
最近更新 更多