如何删除 io.on('connection') 侦听器? [英] How to remove io.on('connection') listener?

查看:26
本文介绍了如何删除 io.on('connection') 侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于 socket.io 服务器的代码:

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);

不起作用(我得到io.removeListener 不是函数").如何删除 on('connection') 侦听器?

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

如果重要的话,我正在开发一个 socket.io 房间管理库,并且正在编写一个重置函数.我在 Mocha 的测试套件之间使用重置功能.我想要重置功能来删除连接侦听器.

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 版本为 1.3.7

Socket.io version is 1.3.7

推荐答案

如果你了解 socket.io 如何处理 .on(),你会发现它使用的是默认的顶级命名空间作为 EventEmitterio.on() 只是将函数调用转发到顶级命名空间对象.因此,您可以获取顶级命名空间对象,然后像这样调用任何 EventEmitter 方法:

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.

这篇关于如何删除 io.on('connection') 侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆