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.

client.js 1.3KB

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