io.js 2.2 KB

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