如何取消订阅 socket.io 订阅? [英] How to unsubscribe from a socket.io subscription?
问题描述
假设有像这样订阅套接字服务器的对象:
Suppose there are objects making subscriptions to a socket server like so:
socket.on('news', obj.socketEvent)
这些对象的生命周期很短并且经常被创建,从而产生很多订阅.这看起来像是内存泄漏和容易出错的情况,可以通过这种方式直观地防止:
These objects have a short life span and are frequently created, generating many subscriptions. This seems like a memory leak and an error prone situation which would intuitively be prevented this way:
socket.off('news', obj.socketEvent)
在对象被删除之前,但可惜的是,套接字中没有 off
方法.有没有其他方法可以解决这个问题?
before the object is deleted, but alas, there isn't an off
method in the socket. Is there another method meant for this?
编辑:没有找到答案,我正在分配一个空白方法来覆盖原始事件处理程序的包装方法,示例如下.
Edit: having found no answer I'm assigning a blank method to overwrite the wrapper method for the original event handler, an example follows.
var _blank = function(){};
var cbProxy = function(){
obj.socketEvent.apply(obj, arguments)
};
var cbProxyProxy = function(){
cbProxy.apply ({}, arguments)
}
socket.on('news', cbProxyProxy);
// ...and to unsubscribe
cbProxy = _blank;
推荐答案
从socket.io.js的源码看(在任何地方的文档中都找不到),我找到了这两个功能:
From looking at the source of socket.io.js (couldn't find it in documentation anywhere), I found these two functions:
removeListener = function(name, fn)
removeAllListeners = function(name)
我在我的应用中成功使用了 removeAllListeners
;您应该可以从以下选项中进行选择:
I used removeAllListeners
successfully in my app; you should be able to choose from these:
socket.removeListener("news", cbProxy);
socket.removeAllListeners("news");
另外,我认为您的 cbProxy = _blank
解决方案实际上行不通;这只会影响 cbProxy
变量,不会影响任何实际的 socket.io 事件.
Also, I don't think your solution of cbProxy = _blank
would actually work; that would only affect the cbProxy
variable, not any actual socket.io event.
这篇关于如何取消订阅 socket.io 订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!