javascript - Correct use of socket.io events's callbacks -
i reading this interesting introductory article how socket.io's events , callbacks work.
i decided give first try follows.
first try
server.js
// client socket client client.on('foo' , function(callback){ callback("hello world"); });
client.js
// server socket server server.emit('foo', function(msg){ alert(msg); });
well, happens didn't work (the server throws exception telling callback
not function). trying solve that, found this answer explaining how right way. well, didn't work either. few modifications , got this...
second try
server.js
// client socket client client.on('foo' , function(name, callback){ callback("hello world"); });
client.js
// server socket server server.emit('foo',{},function(msg){ alert(msg); });
well, works perfectly, having add "name" parameter , empty hash don't use seems a not-so-good solution.
i tried find explanation of in amazingly incomplete socket.io's documentation, found no explanation beheaviour, why i'm asking here.
another doubt have if possible same other side (i.e., server sending callback client, , callback getting executed in server), haven't tried yet.
tl;dr: why first try doesn't work , second 1 does? there way avoid useless empty hash , name
argument?. work same both ways? (server→client , client→server).
the empty object doesn't have object, can virtually anything, such string, or maybe null (haven't tried that). name
parameter isn't "name" parameter, it's whatever data passed client (again, empty object using, or else). better generic parameter name might data
. sure, call waste, it's 2 characters you're transferring, , of time you'll find use data.
the third argument you're passing emit
(a function) optional callback parameter, , since it's working, you're using right.
as going in reverse direction, i've never tried either. it's work, if doesn't, have send unique id along each of push events, , have client emit event server id, , write code on server reassociates event original push event. use counter on each socket push id, , use combination of socket.id
, event.id
unique identifier.
Comments
Post a Comment