A library to make working with websockets easier.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. (function() {
  2. function SockSugar(url) {
  3. this._sock = new WebSocket(url);
  4. this._cbs = {};
  5. this._reqs = [];
  6. this._requestId = 1;
  7. this._sock.onopen = function() {
  8. this.emit("ready");
  9. }.bind(this);
  10. this._sock.onclose = function(evt) {
  11. this.emit("close");
  12. }.bind(this);
  13. this._sock.onmessage = function(evt) {
  14. var obj = JSON.parse(evt.data);
  15. if (obj.err) {
  16. this._reqs[obj.r](obj.err);
  17. } else if (obj.r) {
  18. this._reqs[obj.r](null, obj.d);
  19. } else if (obj.evt) {
  20. this.emit(obj.evt, obj.d);
  21. } else {
  22. throw new Error("Invalid message.");
  23. }
  24. delete this._reqs[obj.r];
  25. }.bind(this);
  26. }
  27. SockSugar.prototype.send = function(name, data, cb) {
  28. this._reqs[this._requestId] = cb;
  29. this._sock.send(JSON.stringify({
  30. r: this._requestId++,
  31. d: data,
  32. n: name
  33. }));
  34. }
  35. SockSugar.prototype.on = function(name, func) {
  36. if (this._cbs[name] === undefined)
  37. this._cbs[name] = [];
  38. this._cbs[name].push(func);
  39. }
  40. SockSugar.prototype.emit = function(name, data) {
  41. if (this._cbs[name] === undefined)
  42. return;
  43. this._cbs[name].forEach(function(cb) {
  44. cb(data);
  45. });
  46. }
  47. window.SockSugar = SockSugar;
  48. })();