1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- (function() {
- function post(url, cb) {
- let cbd = false;
- function c(err, res) {
- if (cbd) return;
- cbd = true;
- cb(err, res);
- }
-
- setTimeout(() => c("ETIMEDOUT"), 5000);
-
- fetch(url, { method: "POST" })
- .then(response => response.json())
- .then(obj => {
- if (obj.error)
- c(obj.error);
- else
- c(null, obj);
- })
- .catch(err => {
- c(err);
- });
- }
-
- 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) {
- // Retry on error
- if (err === "ENOTREGISTERED") {
- console.log("Not registered, reregistering");
- setTimeout(init, 2000);
- return;
- } else if (err == "ETIMEDOUT") {
- console.log("Timed out.");
- setTimeout(await, 0);
- return;
- } else if (err) {
- console.error("Error:", err.toString());
- emit("$error", err);
- setTimeout(init, 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;
- }
- })();
|