HLRTest/render/utils.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2023-11-28 18:32:40 +01:00
"use strict";
function $(name) { return document.getElementById(name); }
function Tag(name, attrs, body, children, eventName, eventHandler) {
2023-11-28 18:32:40 +01:00
let elem = document.createElement(name);
if (body) {
// elem.innerHTML = body; // innerHTML is ugly (slow, overwrite childNodes)
let textNode = document.createTextNode(body);
elem.appendChild(textNode);
2023-11-28 18:32:40 +01:00
}
for (let k in attrs) {
elem.setAttribute(k, attrs[k]);
}
for (let i in children) {
elem.appendChild(children[i]);
}
if (eventName && eventHandler) {
elem.addEventListener(eventName, eventHandler);
}
2023-11-28 18:32:40 +01:00
return elem;
}
function Text(text) {
return document.createTextNode(text);
}
function debounce(func, cancelFunc = ()=>{}, timeout = 500) {
2023-11-28 18:32:40 +01:00
let timer;
return (...args) => {
cancelFunc();
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
}
}
function sendRequest(method, path, query, body, funcDone, funcError) {
let req = new XMLHttpRequest();
if (query) {
let params = new URLSearchParams(query);
path = path + "?" + params.toString();
}
req.open(method, path, true);
req.onreadystatechange = function () {
if (req.readyState == XMLHttpRequest.DONE) {
let status = req.status;
if (status === 0 || (status >= 200 && status < 400)) {
if (funcDone)
funcDone(req.responseText, status);
} else {
if (funcError)
funcError(req.responseText, status);
}
}
}
if (body) {
req.setRequestHeader("Content-Type", "application/json");
console.log("SENDING", body)
req.send(JSON.stringify(body));
} else {
req.send();
}
return req;
}