socket.io,dynamic添加消息处理程序
我愉快地写了一个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
callback触发器(假设在绑定它几秒钟后), for
循环完成, method
variables成为最后一个值。
要解决这个问题,你可以使用一些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) }
当你第一次看到它的时候,这个“魔法”是难以理解的,但是当你得到它的时候,事情就变得清晰了:)