AxD*_*AxD 1 javascript google-chrome web-component shadow-dom custom-element
我正在为我的 Web 组件实现 Orchestrator 模式,如下所示:
<body>
<my-controller>
<div>
<my-list>
<span>
<my-item></my-item>
</span>
</my-list>
</div>
</my-controller>
</body>
Run Code Online (Sandbox Code Playgroud)
我创建的所有自定义元素都使用 Shadow DOM 使用const root = super.attachShadow({mode: "open"}); root.appendChild(...);.
从我的内部 Web 组件中,我想在以下位置访问我的my-controller组件connectedCallback():
public connectedCallback(): void
{
if (this.isConnected)
{
for (let node = this.parentElement; node; node = node.parentElement)
if (node instanceof ContainerBase)
{
this._service = (<ContainerBase>node).GetService(this);
break;
}
if (this._service) this.Reset();
else throw new ReferenceError(`${this.nodeName.toLowerCase()}: Couldn't find host element while connecting to document.`);
}
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是:我只能访问直接父网络控件。
所以,如果connectedCallback()被调用<my-list>我可以到达<my-controller>,但如果connectedCallback()被调用<my-item>我只能到达<span>。<my-list>当我开始搜索时,我什至无法到达<my-item>。
即使我在connectedCallback()被调用后遍历 DOM 树,<span>当我从<my-item>.
这是故意的吗?
为什么可以我到达从第一嵌套一个外部Web组件,而我不能达到从第二嵌套一个第一嵌套的Web部件?
如何从任何嵌套级别完全向上 DOM 树?
When you define a Custom Element content whith a Shadow DOM, you create a distinct DOM tree. The Shadow DOM is a DocumentFragment with no root element.
As a consequence, you cannot reach its (intuitive) ancestor simply by walking the DOM up by the parentElement property.
To reach the host element of a Shadow DOM, instead use getRootNode() combined with host.
From <my-item>'s connectedCallback() method:
connectedCallback() {
var parent = this.getRootNode().host
console.log( parent.localNode ) // my-list
}
Run Code Online (Sandbox Code Playgroud)
If you want to get an ancestor, you could try this recursive function.
| 归档时间: |
|
| 查看次数: |
1796 次 |
| 最近记录: |