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.
 
 
 

73 lines
1.7 KiB

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