io.js 2.1 KB

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