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

client.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. (function() {
  2. function post(url, cb) {
  3. var xhr = new XMLHttpRequest();
  4. xhr.addEventListener("load", function() {
  5. try {
  6. var obj = JSON.parse(xhr.responseText);
  7. } catch (err) {
  8. console.log(xhr.responseText);
  9. cb(err);
  10. }
  11. if (obj.error) {
  12. cb(obj.error);
  13. } else {
  14. cb(null, obj);
  15. }
  16. });
  17. xhr.addEventListener("error", function(err) {
  18. cb(err);
  19. });
  20. xhr.open("POST", url);
  21. xhr.send();
  22. }
  23. window.WebEvents = function() {
  24. var self = {};
  25. var cbs = {};
  26. var key = null;
  27. function emit(name, args) {
  28. if (!cbs[name])
  29. return;
  30. cbs[name].forEach(function(cb) {
  31. cb(args);
  32. });
  33. }
  34. function init() {
  35. console.log("init...");
  36. post("/webevents/register", function(err, res) {
  37. console.log("Init done", err ? "with errors" : "no errors");
  38. // Retry on error
  39. if (err) {
  40. console.log(err);
  41. setTimeout(function() { init() }, 2000);
  42. return;
  43. }
  44. self.emit("connection");
  45. key = res.key;
  46. await();
  47. });
  48. }
  49. function await() {
  50. console.log("await...");
  51. post("/webevents/await/"+key, function(err, res) {
  52. console.log("Await done", err ? "with errors" : "no errors");
  53. // Retry on error
  54. if (err === "ENOTREGISTERED") {
  55. console.log("Not registered, reregistering");
  56. setTimeout(function() { init() }, 2000);
  57. return;
  58. } else if (err) {
  59. console.error(err);
  60. setTimeout(function() { await() }, 2000);
  61. return;
  62. }
  63. res.forEach(function(evt) {
  64. emit(evt.name, evt.args);
  65. });
  66. await();
  67. });
  68. }
  69. self.on = function(name, cb) {
  70. if (!cbs[name])
  71. cbs[name] = [];
  72. cbs[name].push(cb);
  73. };
  74. init();
  75. return self;
  76. }
  77. })();