2024-04-14 12:41:22 +00:00
|
|
|
import { Behavior, fireEvents, registerBehavior, swap } from "./index";
|
2024-04-11 17:07:20 +00:00
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
class FetchBehavior extends Behavior {
|
2024-04-11 17:07:20 +00:00
|
|
|
constructor(element) {
|
2024-04-14 12:41:22 +00:00
|
|
|
super(element);
|
|
|
|
|
2024-04-11 17:07:20 +00:00
|
|
|
const eventName = element.getAttribute("ld-on");
|
2024-04-14 12:41:22 +00:00
|
|
|
const interval = parseInt(element.getAttribute("ld-interval")) * 1000;
|
|
|
|
|
|
|
|
this.onFetch = this.onFetch.bind(this);
|
|
|
|
this.onInterval = this.onInterval.bind(this);
|
|
|
|
|
|
|
|
element.addEventListener(eventName, this.onFetch);
|
|
|
|
if (interval) {
|
|
|
|
this.intervalId = setInterval(this.onInterval, interval);
|
|
|
|
}
|
|
|
|
}
|
2024-04-11 17:07:20 +00:00
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
destroy() {
|
|
|
|
if (this.intervalId) {
|
|
|
|
clearInterval(this.intervalId);
|
|
|
|
}
|
2024-04-11 17:07:20 +00:00
|
|
|
}
|
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
async onFetch(maybeEvent) {
|
|
|
|
if (maybeEvent) {
|
|
|
|
maybeEvent.preventDefault();
|
|
|
|
}
|
2024-04-11 17:07:20 +00:00
|
|
|
const url = this.element.getAttribute("ld-fetch");
|
|
|
|
const html = await fetch(url).then((response) => response.text());
|
|
|
|
|
|
|
|
const target = this.element.getAttribute("ld-target");
|
|
|
|
const select = this.element.getAttribute("ld-select");
|
|
|
|
swap(this.element, html, { target, select });
|
|
|
|
|
|
|
|
const events = this.element.getAttribute("ld-fire");
|
|
|
|
fireEvents(events);
|
|
|
|
}
|
2024-04-14 12:41:22 +00:00
|
|
|
|
|
|
|
onInterval() {
|
|
|
|
if (Behavior.interacting) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.onFetch();
|
|
|
|
}
|
2024-04-11 17:07:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
registerBehavior("ld-fetch", FetchBehavior);
|