socket.io 删除特定的监听器 [英] socket.io Removing specific listener
问题描述
我使用的是 Socket.io v0.9.16 和铬 34
I'm using Socket.io v0.9.16 and Chrome 34
我正在尝试删除特定的侦听器,或取消订阅特定的订阅
I'm trying to remove a specific listener, or unsubscribe from a specific subscription
像这样:
socket.on('testComplete',function(data){
console.log('test complete',data);
});
function emitTest(){
console.log('emitting test');
socket.emit('test','first emit');
}
function removeListener(){
socket.removeListener('testComplete');
}
如果我调用 emitTest
函数,然后调用 removeListener
函数,当我调用 'test complete'
时,我仍然看到 'test complete'
消息再次代码>emitTest.监听器应该已经被移除,如果套接字函数甚至可以工作.
If I call the emitTest
function, and then the removeListener
function, I still see the 'test complete'
message when I call emitTest
again. The listener should have been removed, if the socket function even works.
我正在寻找一种方法来删除实际有效的特定侦听器.
I'm looking for a way to remove a specific listener that actually works.
这个答案说 removeListener 不起作用.
This answer says that removeListener doesn't work.
这样做有什么缺点吗:
socket.removeListener=function(name){
if(socket.$events.hasOwnProperty(name)){
delete socket.$events[name];
}
};
我将一个答案标记为正确,但我在代码中使用了上述内容,因为它更适合我的设计.
I marked an answer as correct, but I'm using the above in my code since it works better with my design.
推荐答案
//To unsubscribe all listeners of an event
socket.off('event-name');
//to unsubscribe a certain listener
socket.off('event-name', listener);
注意socket.off
、socket.removeListener
、socket.removeAllListeners
、socket.removeEventListener
是同义词.
这是在 socket.io v1.4.3 上测试的
This is tested on socket.io v1.4.3
这篇关于socket.io 删除特定的监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!