in node.js
and socket.io
, many events can be handled by one function:
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;
}
}
how do I get the event name, eg, 'async.enum_tag' associated with the socket.on()
?
I don't think the event name is reported to the callback function. You could try something like this:
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'); } );
Or, probably better:
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]);
Also, you may use express.io with express.io-middleware, which adds req.io.event, which store event name and req.io.namespaces which store first part of event name, splitted by ':'.