NodeJS HTTP request connection's close event fired twice
Asked Answered
A

0

2

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)

Ardoin answered 28/8, 2011 at 15:44 Comment(3)
Why not simply use socket.io with the transports limited to xhr (ajax)?Triturate
Because I didn't know about it. Thanks, I will give it a try.Ardoin
Also check out dnode and nowjs (they're callback layers on top of socket.io)Triturate

© 2022 - 2024 — McMap. All rights reserved.