You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

76 lines
1.8 KiB

  1. define([
  2. 'socket',
  3. 'js/system/events'
  4. ], function (
  5. io,
  6. events
  7. ) {
  8. let client = {
  9. doneConnect: false,
  10. init: function (onReady) {
  11. this.socket = io({
  12. transports: ['websocket']
  13. });
  14. this.socket.on('connect', this.onConnected.bind(this, onReady));
  15. this.socket.on('handshake', this.onHandshake.bind(this));
  16. this.socket.on('event', this.onEvent.bind(this));
  17. this.socket.on('events', this.onEvents.bind(this));
  18. this.socket.on('dc', this.onDisconnect.bind(this));
  19. },
  20. onConnected: function (onReady) {
  21. if (this.doneConnect)
  22. this.onDisconnect();
  23. else
  24. this.doneConnect = true;
  25. if (onReady)
  26. onReady();
  27. },
  28. onDisconnect: function () {
  29. window.location = window.location;
  30. },
  31. onHandshake: function () {
  32. events.emit('onHandshake');
  33. this.socket.emit('handshake');
  34. },
  35. request: function (msg) {
  36. this.socket.emit('request', msg, msg.callback);
  37. },
  38. onEvent: function (response) {
  39. events.emit(response.event, response.data);
  40. },
  41. onEvents: function (response) {
  42. //If we get objects, self needs to be first
  43. // otherwise we might create the object (setting his position or attack animation)
  44. // before instantiating it
  45. let oList = response.onGetObject;
  46. if (oList) {
  47. let prepend = oList.filter(o => o.self);
  48. oList.spliceWhere(o => prepend.some(p => p === o));
  49. oList.unshift.apply(oList, prepend);
  50. }
  51. for (let e in response) {
  52. let r = response[e];
  53. //Certain messages expect to be performed last (because the object they act on hasn't been created when they get queued)
  54. r.sort(function (a, b) {
  55. if (a.performLast)
  56. return 1;
  57. else if (b.performLast)
  58. return -1;
  59. return 0;
  60. });
  61. r.forEach(function (o) {
  62. events.emit(e, o);
  63. });
  64. }
  65. }
  66. };
  67. return client;
  68. });