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.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. key = res.key;
  45. await();
  46. });
  47. }
  48. function await() {
  49. console.log("await...");
  50. post("/webevents/await/"+key, function(err, res) {
  51. console.log("Await done", err ? "with errors" : "no errors");
  52. // Retry on error
  53. if (err === "ENOTREGISTERED") {
  54. console.log("Not registered, reregistering");
  55. setTimeout(function() { init() }, 2000);
  56. return;
  57. } else if (err) {
  58. console.error(err);
  59. setTimeout(function() { await() }, 2000);
  60. return;
  61. }
  62. res.forEach(function(evt) {
  63. emit(evt.name, evt.args);
  64. });
  65. await();
  66. });
  67. }
  68. self.on = function(name, cb) {
  69. if (!cbs[name])
  70. cbs[name] = [];
  71. cbs[name].push(cb);
  72. };
  73. init();
  74. return self;
  75. }
  76. })();