title: NodeJS HTTP request connection's close event fired twice
body: <p>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:</p>
  
  <pre><code>request.connection.on('close', function () {
    console.log(request.url);      
    ... 
  }); 
  </code></pre>
  
  <p>The AJAX loop looks like this:</p>
  
  <pre><code>var EventLoop = new (function () {
  
    var self = this;
  
    this.listen = function () {
      $.postJSON(
        'recieve-events', 
        { /* some data not important for this issue */ }, 
        function (data) {
          ...
          self.listen();
        }
      );
    }
  
  })();     
  </code></pre>
  
  <p>This is how the postJSON function is defined:</p>
  
  <pre><code>$.extend({
    postJSON: function (url, data, callback) {
      $.ajax({
        'url': url, 
        'dataType': 'json', 
        'data': data,
        'type': 'POST', 
        'success': callback
      });
    }
  });
  </code></pre>
  
  <p>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? </p>
  
  <p>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)</p>