我很高兴编写了一个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 函数。
有人知道我在这里做错了什么吗?
问题出现是因为到那时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)
}
当你第一次看到它时,这种“魔法”很难理解,但是当你了解它时,事情就变得清晰了:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)