在Socket.IO处理程序中检测事件类型

时间:2011-10-28 10:06:02

标签: javascript node.js socket.io

我是nodeJS和Socket.IO的新手,我遇到了问题。

有没有办法知道Socket.IO处理程序中的事件类型?我有这样的代码:

// Fire the appropriate callback when we receive a message
// that.received is an array of callback functions
for (var event in that.received) {
    socket.on(event, function(message) {
        // Of course, this won't work because of "event" scope
        that.received[event](message, this);
    });
}

所以,我想知道的是触发我的处理程序的“事件”的实际值。 我尝试使用Chrome开发人员工具检查可用变量,但我找不到任何内容。

我需要这样做,因为我正在编写一些围绕Socket.IO的包装类来处理多个套接字(关于回退服务器的长篇大论)。我希望它足够通用,可以将我的处理程序传递给它。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

好的,愚蠢的问题。

我只需要这样做:

// Fire the appropriate callback when we receive a message
for (var event in that.received) {
    socket.on(event, that.received[event]);
}

我将“this”传递给我的回调函数,这只是愚蠢的。我的回调看起来像这样:

function myCallback(message, socket) {
    // Some code...
    socket.emit('ack', message.id);
    // Some code...
}

但我所要做的就是:

function myCallback(message) {
    // Some code...
    this.emit('ack', message.id);
    // Some code...
}

所以我不再有范围问题了。

相关问题