Reputation: 1019
Consider a parent node as such ::-
<poly-parent>
And it has child nodes as :: <poly-child>
I want parent to keep track of the max value of a particular attribute a child can have 'attChild'. I am able to track changes using attChildChanged for the element.
How can parent keep track of max attChild ? ::--
<poly-parent>
<poly-child attChild="2"></poly-child>
<poly-child attChild="4"></poly-child>
</poly-parent>
Is there a polymer(ic) way of doing this ? I want to avoid calling a parent's method from attChildChanged
Upvotes: 0
Views: 850
Reputation: 8065
In the attChildChanged
method you could do something like this:
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;
Assuming this script is scoped to the <poly-parent>
the document would be the root of it's shadow DOM and it would be able to access the elements. If you're trying to run your JS outside of the shadow DOM and the <poly-child>
elements are in the shadow DOM, you'll have to pierce through the shadow DOM using the .shadowRoot
property.
Edit
Using mutation observers in the <poly-parent>
you could do this
//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);
}
Upvotes: 0