【发布时间】: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