info-ajax.js 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('inherits')
  4. , objectUtils = require('./utils/object')
  5. ;
  6. var debug = function() {};
  7. if (process.env.NODE_ENV !== 'production') {
  8. debug = require('debug')('sockjs-client:info-ajax');
  9. }
  10. function InfoAjax(url, AjaxObject) {
  11. EventEmitter.call(this);
  12. var self = this;
  13. var t0 = +new Date();
  14. this.xo = new AjaxObject('GET', url);
  15. this.xo.once('finish', function(status, text) {
  16. var info, rtt;
  17. if (status === 200) {
  18. rtt = (+new Date()) - t0;
  19. if (text) {
  20. try {
  21. info = JSON.parse(text);
  22. } catch (e) {
  23. debug('bad json', text);
  24. }
  25. }
  26. if (!objectUtils.isObject(info)) {
  27. info = {};
  28. }
  29. }
  30. self.emit('finish', info, rtt);
  31. self.removeAllListeners();
  32. });
  33. }
  34. inherits(InfoAjax, EventEmitter);
  35. InfoAjax.prototype.close = function() {
  36. this.removeAllListeners();
  37. this.xo.close();
  38. };
  39. module.exports = InfoAjax;