socket.io删除特定的侦听器 [英] socket.io Removing specific listener

查看:802
本文介绍了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);
}

这篇关于socket.io删除特定的侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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