如何取消订阅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屋!