2014-02-08 22 views
2

我写了一个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函数。

任何任何线索我在这里做错了吗?

+0

你有更多的代码,比如你用来触发事件的代码吗? –

回答

3

问题出现是因为到那个时候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) 
} 

这种“神奇”是很难理解当你第一次看到它,但是当你得到它,事情变得清晰:)

+0

哇,非常感谢这个快速和工作的答案! (除了一个小错字,第二行应该有}而不是] :) –

+0

@ user3287210是的,你是对的。固定! – Curious