javascript-socket.io,如何从函数中获取事件名称?
作者:互联网
在node.js和socket.io中,许多事件可以由一个函数处理:
socket.on( 'async.popular_qtns', rows.bind(socket) );
socket.on( 'async.recent_qtns', rows.bind(socket) );
socket.on( 'async.enum_chn', rows.bind(socket) );
socket.on( 'async.enum_tag', rows.bind(socket) );
function rows() {
var socket = this;
switch( socket.?? ) {
case 'async.popular_qtns': // blah blah
break;
case 'async.recent_qtns': // blah blah
break;
}
}
如何获取与socket.on()关联的事件名称,例如“ async.enum_tag”?
解决方法:
我认为事件名称没有报告给回调函数.您可以尝试这样的事情:
var rowsBound = rows.bind(socket);
socket.on( 'async.popular_qtns', function() { rowsBound('asyn.popular_qtns'); } );
socket.on( 'async.recent_qtns', function() { rowsBound('asyn.recent_qtns'); } );
socket.on( 'async.enum_chn', function() { rowsBound('asyn.enum_chn'); } );
socket.on( 'async.enum_tag', function() { rowsBound('asyn.enum_tag'); } );
或者,可能更好:
var rowsBound = rows.bind(socket),
events = ['async.popular_qtns', 'async.recent_qtns', 'async.enum_chn', 'async.enum_tag'];
for (var i in events)
(function(e) { socket.on(e, function() { rowsBound(e); }); })(events[i]);
标签:node-js,socket-io,javascript 来源: https://codeday.me/bug/20191201/2077387.html