我正在构建一个充当套接字客户端和服务器的中间节点服务器,我希望监听后端服务器事件,然后在处理后将事件转发到客户端(浏览器)。
var socket = require('socket.io'),
client = require('socket.io-client');
socket.on('event_name', function(data) {
/* Logic to process response and relay to client */
client.emit(this.event, data); // How can I get name of the outer event?
});
我想在回调中获得event_name
值。我该怎么办?
答案 0 :(得分:6)
我不确定您是否可以从回调中获取事件名称,但您可以解决它。
var socket = require('socket.io');
function registerEvent(eventName, cb) {
socket.on(eventName, function () {
var args = [].slice.apply(arguments);
args.unshift(eventName);
cb.apply(null, args);
});
}
registerEvent('my_event', function (eventName, data) {
// now you can access event name
// it is prepended to arguments
console.log('Event name', eventName);
});
答案 1 :(得分:4)
你可以尝试类似的东西:
// List of events relayed to client
var events = ['first_event', 'second_event', 'third_event'];
for (var i in events)
(function(e) {
socket.on(e, function(data) {
console.log(e); // You have access to the event name
client.emit(e, data); // Relay to client
});
})(events[i]);