io.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 (id.indexOf("$event:") !== -1) {
  45. delete this.socket._callbacks[id];
  46. }
  47. });
  48. },
  49. init: function (url) {
  50. this.socket = window.socket = io(url);
  51. this.socket.on('connect', () => {
  52. onConnectCallbacks.forEach((cb) => {
  53. cb();
  54. });
  55. onConnectCallbacksPersist.forEach((cb) => {
  56. cb();
  57. });
  58. });
  59. this.socket.on('disconnect', () => {
  60. console.log("IO: SOCKET DISCONNECTED");
  61. onDisconnectCallbacks.forEach((cb) => {
  62. cb();
  63. });
  64. onDisconnectCallbacksPersist.forEach((cb) => {
  65. cb();
  66. });
  67. });
  68. this.socket.on('connect_error', () => {
  69. console.log("IO: SOCKET CONNECT ERROR");
  70. onConnectErrorCallbacks.forEach((cb) => {
  71. cb();
  72. });
  73. onConnectErrorCallbacksPersist.forEach((cb) => {
  74. cb();
  75. });
  76. });
  77. this.ready = true;
  78. callbacks.forEach(callback => {
  79. callback(this.socket);
  80. });
  81. callbacksPersist.forEach(callback => {
  82. callback(this.socket);
  83. });
  84. callbacks = [];
  85. callbacksPersist = [];
  86. }
  87. }