io.js 2.2 KB

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