【问题标题】:A web component inside the template of another另一个模板内的 Web 组件
【发布时间】:2015-01-02 10:10:50
【问题描述】:

我有一个自定义元素,它由其他 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

【问题讨论】:

  • 我认为您对
  • @Robert 问题是我发现我上面的代码没有任何问题,你能解释一下它的坏处吗?这当然只是一个简单的例子,我的想法是能够覆盖默认值另一个 html 文件中的模板,如果我想使用聚合物,我不会问;)

标签: dart


【解决方案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

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 2016-08-31
    • 2018-11-10
    • 2017-11-12
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多