我有一个RPG主HTML元素定义如下。我在index.html文件的主体中实例化它。
<link rel="import" href="packages/polymer/polymer.html">
<link rel="import" href="gridlayout.html">
<link rel="import" href="gridtile.html">
<polymer-element name="rpg-main" attributes="">
<template>
<style>
grid-tile {
background: #FF00FF;
width: 50px;
height: 50px
}
:host {
position: absolute;
display: block;
width: 500px;
height: 500px;
}
</style>
<grid-layout rows = "2" cols = "2" spacing = "50px">
<grid-tile>
</grid-tile>
<grid-tile>
</grid-tile>
<grid-tile>
</grid-tile>
<grid-tile>
</grid-tile>
</grid-layout>
</template>
<script type="application/dart" src="rpgmain.dart"></script>
</polymer-element>
正如人们所料,我还定义了网格布局和网格图块元素。在网格布局的构造函数中,我试图引用它的子代。但是当元素在上面的rpg-main类中被实例化时,该元素认为它有0个孩子。
import 'package:polymer/polymer.dart';
import 'dart:html';
@CustomTag('grid-layout')
class GridLayout extends PolymerElement {
@published int rows;
@published int cols;
@published int spacing;
String _px = "px";
String _perc = "%";
GridLayout.created() : super.created() {
print("NUM CHILDREN " + this.children.length.toString());
/** for (int i = 0; i <= this.rows + this.cols - 2; i++) {
Element child = this.children[i];
this.children[i].style.margin = this._parseNum(spacing);
child.style.float = "right";
if (i % this.rows == this.rows) {
child.style.clear = "right";
}
}**/
}
num _parseString(String s) {
print(s.toString());
return num.parse(s.split(_px)[0]);
}
String _parseNum(num n) {
return n.toString() + _px;
}
}
***以上代码打印“NUM CHILDREN:0”
它只是在我的rpg-main元素中实例化,所以我很惊讶它不会将网格块识别为子节点。可能是因为grid-layout元素正在rpg-main自定义元素的模板标签中实例化? (所以也许网格布局不会认为它的孩子处于'光明的dom'?)这将是一种耻辱,但如果是这样,那么解决方法是什么?
答案 0 :(得分:1)
构造函数只是错误的地方。在使用元素之前,您需要允许元素正确初始化。
尝试
@override
void attached() {
super.attached();
print("NUM CHILDREN " + this.children.length.toString());
}
另见Justins回答When is shadowRoot available to a polymer component?