我有一个自定义元素,由2个其他自定义元素扩展
import 'dart:html';
void main() {
document.registerElement('x-c', C);
document.registerElement('x-b', B);
}
class ViewBase extends HtmlElement{
TemplateElement t;
ViewBase.created():super.created(){
t = this.querySelector('template');
var clone = t.content.clone(true);
this.createShadowRoot();
this.shadowRoot.append(clone);
}
}
class B extends ViewBase{
B.created():super.created();
}
class C extends ViewBase{
C.created():super.created();
}
当我尝试做类似以下的事情时
<x-b>
<template>
<p>this is a paragraph in b shadowroot</p>
<x-c>
<template>
<p>this is a paragraph in c shadowroot</p>
</template>
</x-c>
</template>
</x-b>
当超级构造函数激活B元素内的模板时,嵌套的C元素构造函数永远不会被调用,任何想法为什么?
我期望在页面上看到的是
this is a paragraph in b shadowroot
this is a paragraph in c shadowroot
我得到的只是
this is a paragraph in b shadowroot
答案 0 :(得分:1)
您需要使用document.importNode
代替clone
import 'dart:html';
void main() {
document.registerElement('x-c', C);
document.registerElement('x-b', B);
}
class ViewBase extends HtmlElement {
TemplateElement t;
ViewBase.created() : super.created() {
print("ViewBase, ${this.runtimeType}");
var shadow = this.createShadowRoot();
shadow.append(document.importNode((this.querySelector('template') as TemplateElement)
.content, true));
}
}
class B extends ViewBase {
B.created() : super.created() {
print("B, ${this.runtimeType}");
}
}
class C extends ViewBase {
C.created() : super.created(){
print("C, ${this.runtimeType}");
}
}
我在玩游戏时改变了你的代码。你当然可以像问题中的代码一样使用临时变量,而不是像我一样在一行中使用。
另见
- http://www.html5rocks.com/en/tutorials/webcomponents/template/
- http://webcomponents.org/articles/introduction-to-template-element/
- http://www.w3.org/TR/DOM-Level-3-Core/core.html#Core-Document-importNode