简体   繁体   English

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

[英]How do we observe distribution changes on a v0 shadow root?

In v1 shadow roots, we can listen to slotchange on <slot> elements then use slot.assignedNodes() to detect changes. 在v1影子根目录中,我们可以侦听<slot>元素上的slotchange ,然后使用slot.assignedNodes()来检测更改。 I am looking for a way to do it with v0 shadow roots. 我正在寻找一种使用v0阴影根进行处理的方法。

With ShadowDOM v0, is there a way to observe changes in distributed nodes of a <content> element in a shadow root? 使用ShadowDOM v0,是否可以观察影子根中<content>元素的分布式节点中的更改?

The easiest way to implement this would be by using requestAnimationFrame to create a poll loop that calls content.getDistributedNodes() to compare new results with old results, but obviously polling is not ideal and is expensive. 实现此目的的最简单方法是使用requestAnimationFrame创建一个轮询content.getDistributedNodes()的轮询循环,以将新结果与旧结果进行比较,但显然轮询并不理想且昂贵。

How can it be done? 如何做呢?

I had a need for this exact thing about the same time you did. 在您执行操作的同一时间,我确实需要此功能。 I ended up creating a library for this which I have been using for a week or so now in testing. 我最终为此创建了一个库,在测试中已经使用了一周左右。 The library is called content-change . 该库称为content-change It's working well for me, but I'm sure there are plenty of opportunities for improvement. 这对我来说效果很好,但是我敢肯定有很多改进的机会。

It works like this; 它是这样工作的; similarly to the slot element's slotchange event from Shadow DOM v1: 与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
});

The event returned to the listener contains a few different types in the event.details . 返回给侦听器的eventevent.details包含几种不同的类型。 The event.details.type will be one of the three: event.details.type将是以下三个之一:

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

allowing you to react to different scenarios. 让您对不同的情况做出反应。 For example, when nodes added to the host element fulfill the requirement to be distributed to that content element, you will receive the following: 例如,当添加到主机元素的节点满足要分发到该内容元素的要求时,您将收到以下信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM