Skip to content

Commit 7573776

Browse files
Merge pull request #142 from opencomponents/custom-element
Automatic management of lifecycles if supported
2 parents d695376 + 1332b13 commit 7573776

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/oc-client.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ export function createOc(oc) {
5252
let RETRY_SEND_NUMBER = ocConf.retrySendNumber || true;
5353
let POLLING_INTERVAL = ocConf.pollingInterval || 500;
5454
let OC_TAG = ocConf.tag || "oc-component";
55+
let DISABLE_LIFECYCLES = isBool(ocConf.disableLifecycles)
56+
? ocConf.disableLifecycles
57+
: false;
5558
let MESSAGES_ERRORS_HREF_MISSING = "Href parameter missing";
5659
let MESSAGES_ERRORS_RETRY_FAILED =
5760
"Failed to load % component " + RETRY_LIMIT + " times. Giving up";
@@ -670,5 +673,50 @@ export function createOc(oc) {
670673
// render the components
671674
loadAfterReady();
672675

676+
if (window.customElements) {
677+
window.customElements.define(
678+
OC_TAG,
679+
class extends HTMLElement {
680+
#connected = false;
681+
#manageLifecycle = !DISABLE_LIFECYCLES;
682+
// biome-ignore lint/complexity/noUselessConstructor: <explanation>
683+
constructor() {
684+
super();
685+
}
686+
687+
connectedCallback() {
688+
this.#connected = true;
689+
690+
if (
691+
this.getAttribute("disable-lifecycle") == "true" ||
692+
this.getAttribute("disable-lifecycle") == ""
693+
) {
694+
this.#manageLifecycle = false;
695+
} else if (this.getAttribute("disable-lifecycle") == "false") {
696+
this.#manageLifecycle = true;
697+
}
698+
699+
if (this.#manageLifecycle) {
700+
oc.renderNestedComponent(this, () => {});
701+
}
702+
}
703+
704+
disconnectedCallback() {
705+
if (this.#connected) {
706+
this.#connected = false;
707+
const shouldUnmount =
708+
this.#manageLifecycle &&
709+
this.unmount &&
710+
this.getAttribute("data-rendered") == "true";
711+
if (shouldUnmount) {
712+
this.unmount();
713+
this.removeAttribute("data-rendered");
714+
}
715+
}
716+
}
717+
},
718+
);
719+
}
720+
673721
return oc;
674722
}

0 commit comments

Comments
 (0)