[英]Accessing a nested polymer element
假設我已經定義了兩個自定義的Polymer元素
<!-- Define inner elements -->
<polymer-element name="child-el" attributes="foo">
<script>
Polymer('child-el', {
/* -- Attributes ------------------------------------------------ */
foo: 'qux'
/* -- Lifecycle ------------------------------------------------- */
created: function() {
console.log('Creating a Child');
},
/* -- Public Methods -------------------------------------------- */
getFoo: function() {
return [this.foo];
}
});
</script>
</polymer-element>
<!-- Define custom element -->
<polymer-element name="parent-el">
<script>
Polymer('parent-el', {
/* -- Lifecycle ------------------------------------------------- */
created: function() {
console.log('Creating a Container');
},
ready: function() {
// This is the part that doesn't seem to work
console.log(this.children[0].getFoo());
}
});
</script>
</polymer-element>
然后在使用這些元素的標記中:
<container>
<child foo="bar"></child>
<child foo="baz"></child>
</container>
正如我在代碼中評論的那樣,我想使用自定義元素的自定義元素子節點的方法和/或屬性( 而不是模板的子節點)。 當然,我知道不僅僅是簡單地循環一個數組,但是在這一點上我並不完全確定如何基本上訪問每個自定義子類作為它們的Polymer類型。
我希望這是有道理的。
謝謝!
訪問元素的輕DOM子domReady()
的最安全時間是在domReady()
回調中。 created
/ ready
/ attached
可能為時尚早,因為該元素尚未保證在DOM中並且子級已升級。
注意:“container”和“child”不是有效的自定義元素名稱。 你需要在名字的某個地方加上“ - ”。 所以“容器元素”或“孩子們”會沒事的。
在與@ebidel的回答和簡短討論之后,我想出了我的問題的完整解決方案。 基本上,我想在父代碼中訪問父Polymer元素的子Polymer元素,但最終我最終以相反的方式執行它。
經驗教訓是,在調用domReady
,元素已升級為包含您定義的方法。 布埃諾。
<!-- Define inner elements -->
<polymer-element name="child-el" attributes="foo">
<script>
Polymer('child-el', {
/* -- Attributes ------------------------------------------------ */
foo: 'qux'
/* -- Lifecycle ------------------------------------------------- */
created: function() {
console.log('Creating a Child');
},
ready: function () {
// Not ready to access this.parentNode at this point
},
domReady: function () {
this.async(function () {
// By this point this.parentNode is upgraded according to
// http://www.polymer-project.org/resources/faq.html#zerochildren
this.parentNode.doFooWithChild(this);
});
/* -- Public Methods -------------------------------------------- */
getFoo: function() {
return [this.foo];
}
});
</script>
</polymer-element>
<!-- Define custom element -->
<polymer-element name="parent-el">
<script>
Polymer('parent-el', {
/* -- Lifecycle ------------------------------------------------- */
created: function() {
console.log('Creating a Container');
},
ready: function() {
// Not ready to access this.children at this point
},
doFooWithChild: function(child) {
console.log(child.getFoo());
}
});
</script>
</polymer-element>
謝謝您的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.