123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- (function() {
- function post(url, cb) {
- var xhr = new XMLHttpRequest();
-
- let timeout = setTimeout(function() {
- console.log("Timed out, aborting.");
- xhr.abort();
- }, 3000);
-
- xhr.addEventListener("load", function() {
- clearTimeout(timeout);
- try {
- var obj = JSON.parse(xhr.responseText);
- } catch (err) {
- console.log(xhr.responseText);
- cb(err);
- }
-
- if (obj.error) {
- cb(obj.error);
- } else {
- cb(null, obj);
- }
- });
-
- xhr.addEventListener("error", function(err) {
- clearTimeout(timeout);
- cb(err);
- });
- xhr.addEventListener("abort", function(err) {
- clearTimeout(timeout);
- cb(err);
- });
-
- xhr.open("POST", url);
- xhr.send();
- }
-
- window.WebEvents = function() {
- var self = {};
-
- var cbs = {};
- var key = null;
-
- function emit(name, args) {
- if (!cbs[name])
- return;
-
- cbs[name].forEach(function(cb) {
- cb(args);
- });
- }
-
- function init() {
- console.log("init...");
- post("/webevents/register", function(err, res) {
- console.log("Init done,", err ? "with errors" : "no errors");
-
- // Retry on error
- if (err) {
- console.log(err);
- setTimeout(function() { init() }, 2000);
- return;
- }
-
- emit("connection");
- key = res.key;
- await();
- });
- }
-
- function await() {
- post("/webevents/await/"+key, function(err, res) {
- if (err) {
- console.log("Await done, with errors");
- }
-
- // Retry on error
- if (err === "ENOTREGISTERED") {
- console.log("Not registered, reregistering");
- setTimeout(function() { init() }, 2000);
- return;
- } else if (err) {
- console.error(err);
- setTimeout(function() { await() }, 2000);
- return;
- }
-
- res.forEach(function(evt) {
- emit(evt.name, evt.args);
- });
-
- await();
- });
- }
-
- self.on = function(name, cb) {
- if (!cbs[name])
- cbs[name] = [];
-
- cbs[name].push(cb);
- };
-
- init();
-
- return self;
- }
- })();
|