在某个时间点上,父级自定义元素可以访问其子级,然后再为其子级赋予其自定义方法。
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()
是否安全?
归因于自定义元素的upgrading process。>
第一步
:执行document.body.innerHTML = '<custom-parent><custom-child>foo</custom-child></custom-parent>'
时,会将2个元素作为unknown elements插入页面中。第二步
:父元素首先是升级。它可以作为unknown元素访问其子级(然后更新其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>`