我写了一个node.js服务器,它使用socket.io与客户端进行通信。 这一切运作良好。socket.io,动态添加消息处理程序
sessionSockets.on('connection', function (err, socket, session) {
control.generator.apply(socket, [session]);
}
的: 这使我想到另一种方式来组织我的代码,并在发电机的功能像这样添加处理程序socket.on(“连接” ...)处理得有点大,发电机采用包含插座事件及其相应的处理函数的对象:
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函数。
任何任何线索我在这里做错了吗?
你有更多的代码,比如你用来触发事件的代码吗? –