Adam
Adam

Reputation: 20942

Socket.IO first connection

I've been using socket.io version 0.9 and the following code worked fine:

// Socket.IO - Executes for Every Socket Connection 
io.on('connection', function (socket) {
  socket.on('userid', function (userid) {
    socket.userid = userid;
  });
});



// Socket.IO - Executes on First Socket Connection Only
io.once('connection', function (socket) {
    auditMessagesTableForNewMessages(socket);
    auditRelationsTableForNewFriendships(socket);
});

I've just upgraded to Socket.IO 1.3.5 and I've found the method .once() doesn't appear to exist anymore. I need to be able to run a couple of functions on first initiation of the socket (which you can see in the once() function).

Is there a way I can achieve the same outcome with the new socket 1.3.5? eg: run those 2 functions once?

thanks :)

Upvotes: 0

Views: 331

Answers (1)

jfriend00
jfriend00

Reputation: 707976

You can install a regular event handler and then remove the event handler after it is called the first time:

function handleFirstConnection(socket) {
    auditMessagesTableForNewMessages(socket);
    auditRelationsTableForNewFriendships(socket);
    io.removeListener('connection', handleFirstConnection);
}

io.on('connection', handleFirstConnection);

Upvotes: 1

Related Questions