- From: Frank Topel <notifications@github.com>
- Date: Fri, 19 Oct 2018 06:29:48 +0000 (UTC)
- To: w3c/webcomponents <webcomponents@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <w3c/webcomponents/issues/551/431258689@github.com>
So hands down, this is what we're going to give a shot, following what we were able to extract from this and other posts on the children/connectedCallback topic. Comments welcome. Yes, we're aware that it will fail in the edge case which @WebReflection mentioned. If anyone sees any other possible edge case, please let us know. ```javascript class HTMLBaseElement extends HTMLElement { constructor(...args) { const self = super(...args) self.parsed = false // guard to make it easy to do certain stuff only once self.parentNodes = [] return self } setup() { // collect the parentNodes let el = this; while (el.parentNode) { el = el.parentNode this.parentNodes.push(el) } // check if the parser has already passed the end tag of the component // in which case this element, or one of its parents, should have a nextSibling // if not (no whitespace at all between tags and no nextElementSiblings either) // resort to DOMContentLoaded or load having triggered if ([this, ...this.parentNodes].some(el=> el.nextSibling) || document.readyState !== 'loading') { this.childrenAvailableCallback(); } else { this.mutationObserver = new MutationObserver(() => { if (this.nextSibling || this.parentNode.nextSibling || document.readyState !== 'loading') { this.childrenAvailableCallback() this.mutationObserver.disconnect() } }); this.mutationObserver.observe(this, {childList: true}); } } } class MyComponent extends HTMLBaseElement { constructor(...args) { const self = super(...args) return self } connectedCallback() { // when connectedCallback has fired, call super.setup() // which will determine when it is safe to call childrenAvailableCallback() super.setup() } childrenAvailableCallback() { // this is where you do your setup that relies on child access console.log(this.children) // when setup is done, make this information accessible to the element this.parsed = true // this is useful e.g. to only ever attach event listeners to child // elements once using this as a guard } } customElements.define('my-component', MyComponent) ``` -- You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub: https://github.com/w3c/webcomponents/issues/551#issuecomment-431258689
Received on Friday, 19 October 2018 06:30:16 UTC