NodeJS HTTP 请求连接的关闭事件触发两次
我正在 NodeJS 中使用长轮询开发实时 AJAX 应用程序。我想检测用户何时关闭带有待处理的长轮询请求的选项卡。我使用 NodeJS 连接关闭事件:
request.connection.on('close', function () {
console.log(request.url);
...
});
AJAX 循环如下所示:
var EventLoop = new (function () {
var self = this;
this.listen = function () {
$.postJSON(
'recieve-events',
{ /* some data not important for this issue */ },
function (data) {
...
self.listen();
}
);
}
})();
这就是 postJSON 函数的定义方式:
$.extend({
postJSON: function (url, data, callback) {
$.ajax({
'url': url,
'dataType': 'json',
'data': data,
'type': 'POST',
'success': callback
});
}
});
问题是,当我关闭选项卡时,连接关闭事件被触发两次。谁能解释一下为什么以及如何防止这种行为?
我知道,我可以第一次使用计数器并调用回调函数,但我不认为这是一个很好的解决方案,因为关闭已经关闭的东西对我来说没有逻辑意义。 (触发事件两次)
I'm working on realtime AJAX application with long polling in NodeJS. I would like to detect when user closes the tab with pending long-polling request. I use NodeJS connection close event:
request.connection.on('close', function () {
console.log(request.url);
...
});
The AJAX loop looks like this:
var EventLoop = new (function () {
var self = this;
this.listen = function () {
$.postJSON(
'recieve-events',
{ /* some data not important for this issue */ },
function (data) {
...
self.listen();
}
);
}
})();
This is how the postJSON function is defined:
$.extend({
postJSON: function (url, data, callback) {
$.ajax({
'url': url,
'dataType': 'json',
'data': data,
'type': 'POST',
'success': callback
});
}
});
The problem is, that the connection close event is fired twice, when I close the tab. Can anyone explain me why and how to prevent this behaviour?
I know, that I can use counter and call the callback function just first time, but I don't consider this as a nice solution, since it doesn't make logical sense to me to close something, that is already closed. (firing the event twice)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论