Gregory Leleytner
Gregory Leleytner

Reputation: 159

How to set socket.on('action', func) callback for all sockets?

Is there way to set callback on action as default for all sockets which are connected now and will be connected in the future without specifying it on every socket?

Upvotes: 0

Views: 144

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146074

Yes, and in fact this is how the overwhelming majority of event handlers for socket.io applications are bound. You express this by binding the same event to each socket immediately after it is created and connected in the io connect event handler function.

function onFoo () {
  // code to deal with foo event
}
io.on('connection', function (socket) {
  socket.on('foo', onFoo)
})

Because you wrote "without specifying it on every socket", I suspect you may be looking for a more declarative approach, but AFAIK this is the only way. It's very flexible in that you could decide to treat all sockets the same or you could have logic to treat different sockets differently (authenticated vs anonymous for example). But in either case, it is supported by this same event handling mechanism on the io instance.

Upvotes: 1

Related Questions