source: trip-planner-front/node_modules/sockjs-client/lib/transport/receiver/eventsource.js@ bdd6491

Last change on this file since bdd6491 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.5 KB
Line 
1'use strict';
2
3var inherits = require('inherits')
4 , EventEmitter = require('events').EventEmitter
5 , EventSourceDriver = require('eventsource')
6 ;
7
8var debug = function() {};
9if (process.env.NODE_ENV !== 'production') {
10 debug = require('debug')('sockjs-client:receiver:eventsource');
11}
12
13function EventSourceReceiver(url) {
14 debug(url);
15 EventEmitter.call(this);
16
17 var self = this;
18 var es = this.es = new EventSourceDriver(url);
19 es.onmessage = function(e) {
20 debug('message', e.data);
21 self.emit('message', decodeURI(e.data));
22 };
23 es.onerror = function(e) {
24 debug('error', es.readyState, e);
25 // ES on reconnection has readyState = 0 or 1.
26 // on network error it's CLOSED = 2
27 var reason = (es.readyState !== 2 ? 'network' : 'permanent');
28 self._cleanup();
29 self._close(reason);
30 };
31}
32
33inherits(EventSourceReceiver, EventEmitter);
34
35EventSourceReceiver.prototype.abort = function() {
36 debug('abort');
37 this._cleanup();
38 this._close('user');
39};
40
41EventSourceReceiver.prototype._cleanup = function() {
42 debug('cleanup');
43 var es = this.es;
44 if (es) {
45 es.onmessage = es.onerror = null;
46 es.close();
47 this.es = null;
48 }
49};
50
51EventSourceReceiver.prototype._close = function(reason) {
52 debug('close', reason);
53 var self = this;
54 // Safari and chrome < 15 crash if we close window before
55 // waiting for ES cleanup. See:
56 // https://code.google.com/p/chromium/issues/detail?id=89155
57 setTimeout(function() {
58 self.emit('close', null, reason);
59 self.removeAllListeners();
60 }, 200);
61};
62
63module.exports = EventSourceReceiver;
Note: See TracBrowser for help on using the repository browser.