socket.io,动态添加消息处理程序 [英] socket.io, adding message handler dynamically

查看:76
本文介绍了socket.io,动态添加消息处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've written happily a node.js server, which uses socket.io to communicate with the client. this all works well. the socket.on('connection'...) handler got a bit big, which made me think of an alternative way to organize my code and add the handlers in a generator function like this:

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

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

the generator takes an object that contains the socket events and their respective handler function:

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函数。

I was hoping that this would add the socket event handlers to the socket, which it kind of does, but when any event comes in, it always calls the latest one added, in this case always the b-function.

任何人都知道我在这里做错了什么?

Anyone any clues what i am doing wrong here?

推荐答案

问题出现的原因是那时 this.on 回调触发器(让我们说在你绑定之后的几秒钟内, for 循环结束,方法变量成为最后一个值。

The problem appears because by that time this.on callback triggers (let's say in a few seconds after you bind it), the for loop is finished and method variable becomes the last value.

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

To fix that you may use some JavaScript magic:

//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)
}

这个魔术当你第一次看到它时很难理解,但当你得到它时,事情变得清晰了:)

This "magic" is hard to understand when you first see it, but when you get it, the things become clear :)

这篇关于socket.io,动态添加消息处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆