io.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. let callbacks = [];
  2. let callbacksPersist = [];
  3. let onConnectCallbacks = [];
  4. let onDisconnectCallbacks = [];
  5. let onConnectErrorCallbacks = [];
  6. let onConnectCallbacksPersist = [];
  7. let onDisconnectCallbacksPersist = [];
  8. let onConnectErrorCallbacksPersist = [];
  9. export default {
  10. ready: false,
  11. socket: null,
  12. getSocket: function() {
  13. if (arguments[0] === true) {
  14. if (this.ready) arguments[1](this.socket);
  15. else callbacksPersist.push(arguments[1]);
  16. } else {
  17. if (this.ready) arguments[0](this.socket);
  18. else callbacks.push(arguments[0]);
  19. }
  20. },
  21. onConnect: function() {
  22. if (arguments[0] === true) {
  23. onConnectCallbacksPersist.push(arguments[1]);
  24. } else onConnectCallbacks.push(arguments[0]);
  25. },
  26. onDisconnect: function() {
  27. if (arguments[0] === true) {
  28. onDisconnectCallbacksPersist.push(arguments[1]);
  29. } else onDisconnectCallbacks.push(arguments[0]);
  30. },
  31. onConnectError: function() {
  32. if (arguments[0] === true) {
  33. onConnectErrorCallbacksPersist.push(arguments[1]);
  34. } else onConnectErrorCallbacks.push(arguments[0]);
  35. },
  36. clear: () => {
  37. onConnectCallbacks = [];
  38. onDisconnectCallbacks = [];
  39. onConnectErrorCallbacks = [];
  40. callbacks = [];
  41. },
  42. removeAllListeners: function() {
  43. Object.keys(this.socket._callbacks).forEach(id => {
  44. if (
  45. id.indexOf("$event:") !== -1 &&
  46. id.indexOf("$event:keep.") === -1
  47. ) {
  48. delete this.socket._callbacks[id];
  49. }
  50. });
  51. },
  52. init: function(url) {
  53. /* eslint-disable-next-line no-undef */
  54. this.socket = window.socket = io(url);
  55. this.socket.on("connect", () => {
  56. onConnectCallbacks.forEach(cb => {
  57. cb();
  58. });
  59. onConnectCallbacksPersist.forEach(cb => {
  60. cb();
  61. });
  62. });
  63. this.socket.on("disconnect", () => {
  64. console.log("IO: SOCKET DISCONNECTED");
  65. onDisconnectCallbacks.forEach(cb => {
  66. cb();
  67. });
  68. onDisconnectCallbacksPersist.forEach(cb => {
  69. cb();
  70. });
  71. });
  72. this.socket.on("connect_error", () => {
  73. console.log("IO: SOCKET CONNECT ERROR");
  74. onConnectErrorCallbacks.forEach(cb => {
  75. cb();
  76. });
  77. onConnectErrorCallbacksPersist.forEach(cb => {
  78. cb();
  79. });
  80. });
  81. this.ready = true;
  82. callbacks.forEach(callback => {
  83. callback(this.socket);
  84. });
  85. callbacksPersist.forEach(callback => {
  86. callback(this.socket);
  87. });
  88. callbacks = [];
  89. callbacksPersist = [];
  90. }
  91. };