首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >聚合物通过亲本观察子属性

问聚合物通过亲本观察子属性
EN

Stack Overflow用户
提问于 2015-02-23 06:19:17
回答 1查看 826关注 0票数 0

假设父节点如下:-

代码语言:javascript
复制
<poly-parent>

它的子节点为::<poly-child>

我希望父级跟踪一个特定属性的最大值,一个子属性可以具有“attChild”。我能够对元素使用attChildChanged跟踪更改。

家长如何跟踪max attChild?:--

代码语言:javascript
复制
     <poly-parent> 
        <poly-child attChild="2"></poly-child>
        <poly-child attChild="4"></poly-child>
     </poly-parent>

有聚合物(Ic)做这件事的方法吗?我想避免从attChildChanged调用父方法

EN

回答 1

Stack Overflow用户

发布于 2015-02-23 09:06:36

在attChildChanged方法中,您可以这样做:

代码语言:javascript
复制
var max = 0;
for(var i=0; i<document.getElementsByTagName('poly-child').length; i++){
    if(parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild")) > max){
        max = parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild"));
    }
}
return max;

假设这个脚本的作用域为<poly-parent>,那么文档将是它的影子DOM的根,并且它将能够访问元素。如果试图在阴影DOM之外运行JS,而<poly-child>元素位于影子DOM中,则必须使用.shadowRoot属性穿透阴影DOM。

编辑

在<poly-parent>中使用变异观察者可以做到这一点

代码语言:javascript
复制
//The max value
var max = 0;

// select the target nodes
var targets = document.getElementsByTagName('poly-child');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //Check the new max
    max = 0;
    for(var i=0; i<document.getElementsByTagName('poly-child').length; i++){
        if(parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild")) > max){
            max = parseInt(document.getElementsByTagName('poly-child')[i].getAttribute("attChild"));
        }
    }
  });    
});

// configuration of the observer:
var config = { attributes: true };

// pass in the target nodes, as well as the observer options
for(var i=0; i<targets.length; i++){
    observer.observe(targets[i], config);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28667904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档