thatnerd2
thatnerd2

Reputation: 544

How to remove io.on('connection') listener?

I have some code for a socket.io server along the lines of:

var io = require("socket.io");
io = io(server);
io.on('connection', connectionHandler);

This all works great. I'm wondering how I can remove that connection listener - unlike socket, it appears that

io.removeListener('connection', connectionHandler);

doesn't work (I get "io.removeListener is not a function"). How do I remove that on('connection') listener?

If it matters, I'm working on a socket.io room managing library, and am writing a reset function. I'm using the reset function between test suites with Mocha. I'd like the reset function to remove the on connection listener.

Socket.io version is 1.3.7

Upvotes: 3

Views: 1513

Answers (1)

jfriend00
jfriend00

Reputation: 708206

If you work through how socket.io processes .on(), one can figure out that it's using the default top-level namespace as the EventEmitter and io.on() just forwards the function call to the top-level namespace object. So, you can get the top level namespace object and then just call any EventEmitter method on it like this:

var nsp = io.of('/');
nsp.removeListener('connection', connectionHandler);

I have verified that this works in my own test app and stepped through it in the debugger to verify it was working as expected.

Upvotes: 5

Related Questions