io.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. this.socket = window.socket = io(url);
  57. this.socket.on("connect", () => {
  58. callbacks.onConnect.temp.forEach(cb => cb());
  59. callbacks.onConnect.persist.forEach(cb => cb());
  60. });
  61. this.socket.on("disconnect", () => {
  62. console.log("IO: SOCKET DISCONNECTED");
  63. callbacks.onDisconnect.temp.forEach(cb => cb());
  64. callbacks.onDisconnect.persist.forEach(cb => cb());
  65. });
  66. this.socket.on("connect_error", () => {
  67. console.log("IO: SOCKET CONNECT ERROR");
  68. callbacks.onConnectError.temp.forEach(cb => cb());
  69. callbacks.onConnectError.persist.forEach(cb => cb());
  70. });
  71. this.ready = true;
  72. callbacks.general.temp.forEach(callback => callback(this.socket));
  73. callbacks.general.persist.forEach(callback => callback(this.socket));
  74. callbacks.general.temp = [];
  75. callbacks.general.persist = [];
  76. }
  77. };