socket.io删除特定的侦听器
我正在使用Socket.io v0.9.16和
Chrome 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
function,然后是 removeListener
函数,当我调用'test complete'消息再次c $ c> 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.
这样做是否有任何缺点:
Is there any downside to just doing this:
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.
你需要将监听器功能传递给 removeListener
。
You need to pass in the listener function to removeListener
.
function testFun(data){
console.log('test complete',data);
}
socket.on('testComplete', testFun);
function emitTest(){
console.log('emitting test');
socket.emit('test','first emit');
}
function removeListener(){
socket.removeListener('testComplete', testFun);
}