javascript - event handler that knows the event name -
i have socket.io server generates many events, , want catch of them , print similar message. right now, this:
for (var event in {eventa: 1, eventb: 1, eventc: 1}) { this.translationsocket.on(event, function(result) { console.log("server sent event of type "+event); }); }
when server sends eventa, eventb , eventc, see this:
server sent event of type eventc server sent event of type eventc server sent event of type eventc
i.e. program catches events, displays type of eventc...
i tried following variations:
- remove "var" before "event" inside "for": "for (event ..."
- adding statement 'var msg = "server sent event of type "+event;' either before 'on' statement or before 'console.log' statement, , 'console.log(msg)'.
none of these variations worked...
what should do?
this has nothing socket.io or node.js, known javascript "quirk". value of event
evaluated when code executed, when loop finished. need wrap thing function call preserve value.
var listen = function(socket, event) { socket.on(event, function(result) { console.log("server sent event of type "+event); }); } (var event in {eventa: 1, eventb: 1, eventc: 1}) { listen(event); }
or (shorter version):
for (var event in {eventa: 1, eventb: 1, eventc: 1}) { (function(event) { this.translationsocket.on(event, function(result) { console.log("server sent event of type "+event); }); })(event); }
Comments
Post a Comment