This library provides an easy way to send events to a web browser (or any other client) over HTTP.
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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. (function() {
  2. function post(url, cb) {
  3. let cbd = false;
  4. function c(err, res) {
  5. if (cbd) return;
  6. cbd = true;
  7. cb(err, res);
  8. }
  9. setTimeout(() => c("ETIMEDOUT"), 5000);
  10. fetch(url, { method: "POST" })
  11. .then(response => response.json())
  12. .then(obj => {
  13. if (obj.error)
  14. c(obj.error);
  15. else
  16. c(null, obj);
  17. })
  18. .catch(err => {
  19. c(err);
  20. });
  21. }
  22. window.WebEvents = function() {
  23. var self = {};
  24. var cbs = {};
  25. var key = null;
  26. function emit(name, args) {
  27. if (!cbs[name])
  28. return;
  29. cbs[name].forEach(function(cb) {
  30. cb(args);
  31. });
  32. }
  33. function init() {
  34. console.log("init...");
  35. post("/webevents/register", function(err, res) {
  36. console.log("Init done,", err ? "with errors" : "no errors");
  37. // Retry on error
  38. if (err) {
  39. console.log(err);
  40. setTimeout(function() { init() }, 2000);
  41. return;
  42. }
  43. emit("connection");
  44. key = res.key;
  45. await();
  46. });
  47. }
  48. function await() {
  49. post("/webevents/await/"+key, function(err, res) {
  50. // Retry on error
  51. if (err === "ENOTREGISTERED") {
  52. console.log("Not registered, reregistering");
  53. setTimeout(init, 2000);
  54. return;
  55. } else if (err == "ETIMEDOUT") {
  56. console.log("Timed out.");
  57. setTimeout(await, 0);
  58. return;
  59. } else if (err) {
  60. console.error("Error:", err.toString());
  61. emit("$error", err);
  62. setTimeout(init, 2000);
  63. return;
  64. }
  65. res.forEach(function(evt) {
  66. emit(evt.name, evt.args);
  67. });
  68. await();
  69. });
  70. }
  71. self.on = function(name, cb) {
  72. if (!cbs[name])
  73. cbs[name] = [];
  74. cbs[name].push(cb);
  75. };
  76. init();
  77. return self;
  78. }
  79. })();