我们如何观察v0影子根上的分布变化?

时间:2016-11-30 04:47:08

标签: javascript web-component shadow-dom

在v1影子根中,我们可以在slotchange元素上收听<slot>,然后使用slot.assignedNodes()来检测更改。我正在寻找一种方法来使用v0阴影根。

使用ShadowDOM v0,有没有办法观察阴影根中<content>元素的分布式节点的变化?

实现这一目标的最简单方法是使用requestAnimationFrame创建一个调用循环,调用content.getDistributedNodes()来将新结果与旧结果进行比较,但显然轮询并不理想且价格昂贵。

怎么做?

1 个答案:

答案 0 :(得分:1)

在你做的同时我需要这个确切的事情。我最终为此创建了一个库,我已经使用了一周左右的时间进行测试。该库名为content-change。它对我有用,但我确信有很多改进的机会。

它的作用是这样的;类似于Shadow DOM v1中的slot元素slotchange事件:

// Because this is non-spec, specify internally which components get to be watched
// "this" is the host element
ContentChange.watch(this);

const contentElement = shadow.querySelector('someContentSelector');
contentElement.addEventListener('contentchange', e => {
    // React to distributed node changes for this content element
});

返回到侦听器的eventevent.details中包含几种不同的类型。 event.details.type将是三个中的一个:

  • "nodesAdded"
  • "nodesRemoved"
  • "mutation"

允许您对不同的场景做出反应。例如,当添加到主机元素的节点满足要分发给该内容元素的要求时,您将收到以下内容:

{
    "type": "nodesAdded",
    "nodesAdded": [Nodes] // An array of newly distributed nodes
}