io.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. const passcode = localStorage.getItem("passcode") || "";
  57. this.socket = window.socket = io(url, {
  58. query: `passcode=${passcode}`
  59. });
  60. this.socket.on("connect", () => {
  61. callbacks.onConnect.temp.forEach(cb => cb());
  62. callbacks.onConnect.persist.forEach(cb => cb());
  63. });
  64. this.socket.on("disconnect", () => {
  65. console.log("IO: SOCKET DISCONNECTED");
  66. callbacks.onDisconnect.temp.forEach(cb => cb());
  67. callbacks.onDisconnect.persist.forEach(cb => cb());
  68. });
  69. this.socket.on("connect_error", () => {
  70. console.log("IO: SOCKET CONNECT ERROR");
  71. callbacks.onConnectError.temp.forEach(cb => cb());
  72. callbacks.onConnectError.persist.forEach(cb => cb());
  73. });
  74. this.socket.on("error", err => {
  75. console.log("IO: SOCKET ERROR");
  76. if (err.type && err.type === "CONNECT_ERROR") {
  77. callbacks.onConnectError.temp.forEach(cb => cb());
  78. callbacks.onConnectError.persist.forEach(cb => cb());
  79. }
  80. });
  81. this.ready = true;
  82. callbacks.general.temp.forEach(callback => callback(this.socket));
  83. callbacks.general.persist.forEach(callback => callback(this.socket));
  84. callbacks.general.temp = [];
  85. callbacks.general.persist = [];
  86. }
  87. };