在某个时间点上,父级自定义元素可以访问其子级,然后再为其子级使用其自定义方法。
class CustomParent extends HTMLElement {
connectedCallback() {
// works
this.children[0].textContent = "bar";
// works
setTimeout(() => this.children[0].test(), 0);
// throws a Type error
this.children[0].test();
}
}
customElements.define("custom-parent", CustomParent);
class CustomChild extends HTMLElement {
test() {
this.textContent = "baz";
}
}
customElements.define("custom-child", CustomChild);
document.body.innerHTML = `
<custom-parent>
<custom-child>foo</custom-child>
</custom-parent>
`;
如何做到这一点,是否可以推迟this.children[0].test()
?
这是由于自定义元素的升级过程。
第一步:执行时,会将document.body.innerHTML = '<custom-parent><custom-child>foo</custom-child></custom-parent>'
2个元素作为未知元素插入到页面中。
第二步:首先升级父元素。它可以textContent
作为未知元素访问其子级(然后更新其属性)。但是它无法访问自定义元素test()
方法...因为它还不是自定义元素!
第三步:子元素在升级后立即升级,现在有了一个test()
方法。
第四步:延迟的test()
呼叫在逻辑上有效:-)
请参见下面的示例。它querySelectorAll( ':not(:defined)' )
用来表明孩子在其父母之后被升级。
class CustomParent extends HTMLElement {
constructor() { super() ; console.log( 'parent upgraded') }
connectedCallback() {
console.log( 'parent connected', this.children[0].outerHTML )
// works
this.children[0].textContent = 'bar'
// works
setTimeout( () => this.children[0].test() )
// throws a Type error
try {
this.children[0].test()
} catch ( e ) {
//this shows the parent is upgraded, but not its child
var not_upgraded = document.querySelectorAll( ':not(:defined)' )
console.log( 'not upgraded: ', ...not_upgraded )
}
}
}
customElements.define( 'custom-parent', CustomParent )
class CustomChild extends HTMLElement {
constructor() { super() ; console.log( 'child upgraded') }
test() { this.textContent = 'baz' }
}
customElements.define( 'custom-child', CustomChild )
document.body.innerHTML = `
<custom-parent>
<custom-child>foo</custom-child>
</custom-parent>`
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句