在v1阴影根中,我们可以监听<slot>元素上的slotchange,然后使用slot.assignedNodes()检测更改。我正在寻找一种方法来做它与v0阴影根。
使用ShadowDOM v0,是否有一种方法可以观察影子根中<content>元素的分布式节点的变化?
实现这一点的最简单方法是使用requestAnimationFrame创建一个轮询循环,该循环调用content.getDistributedNodes()来比较新结果和旧结果,但显然轮询并不理想,而且代价很高。
怎么做呢?
发布于 2016-12-21 18:12:39
就在你做这件事的同一时间,我需要这件事。最后,我为此创建了一个库,我已经在测试中使用了一个星期左右。这个库名为内容变化。这对我来说很好,但我相信有很多改进的机会。
它的工作方式如下所示;类似于来自Shadow 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
});返回给侦听器的event包含event.details中的几个不同类型。event.details.type将是其中之一:
"nodesAdded""nodesRemoved""mutation"让你对不同的场景做出反应。例如,当添加到主机元素的节点满足分发到该内容元素的要求时,您将收到以下信息:
{
"type": "nodesAdded",
"nodesAdded": [Nodes] // An array of newly distributed nodes
}https://stackoverflow.com/questions/40880512
复制相似问题