【问题标题】:Using template defined in light dom inside a Polymer element使用在 Polymer 元素内的 light dom 中定义的模板
【发布时间】:2014-02-03 07:48:22
【问题描述】:

我正在尝试将模板从 DOM 移动到元素内部。

这是我的元素:

<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../polymer-ui-icon/polymer-ui-icon.html">

<polymer-element name="bt-sortable-list" attributes="drag name list">
  <template>
    BOOM
    <template binding ref="itemTemplate" repeat="{{list}}" id="repeatTemplate">
    </template>
    <template id="itemTemplate">
    </template>
  </template>
  <script>
    Polymer('bt-sortable-list', {
      ready: function() {
        var div = document.createElement('div');
        contentStr = this.trim(innerHTML);
        var parsed = markdown.toHTML(content);
        this.$.itemTemplate.innerHTML = parsed;
        this.list = [{name: 'Item 1', id: 'item1'}, {name: 'Item 2', id: 'item2'}, {name: 'Item 3', id: 'item3'}];
        this.$.repeatTemplate.model = this.list;
      }
    });

  </script>
</polymer-element>

这是我的 html 文件:

<!doctype html>
<html>
<head>
  <script src="/platform/platform.js"></script>
  <link rel="import" href="/bt-sortable-list/bt-sortable-list.html">
</head>
<body>
  <h3>Sortable List</h3>
  <bt-sortable-list>
  <template 
      Name {{name}}
  </template>
  </bt-sortable-list>
</body>
</html>

我似乎无法让 test.html 中的模板在 bt-sortable-list 自定义元素中使用。一般的想法是自定义元素将处理列表和其他事情,同时让使用该元素的 html 定义列表元素的显示方式。我已经尝试以编程方式添加模板,如图所示。我也试过在 bt-sortable-list 元素下没有模板。我还尝试使用内容元素来获取 test.html 中的模板内容。

任何建议将不胜感激。

【问题讨论】:

    标签: javascript html polymer web-component


    【解决方案1】:

    要使用自定义元素的(light dom)内容,您需要在元素中包含一个插入点 (&lt;content&gt;):

    http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees

    但是,插入点纯粹是用于在 shadow DOM 中渲染节点的占位符。您所追求的有点不同,因为它使用 Polymer 的数据绑定功能将 Polymer 元素外部的 light dom 世界与内部的 shadow dom 世界联系起来。

    我能够通过在ready() 中动态创建&lt;template&gt; 并使用ref 来引用它:

    var t = document.createElement('template');
    t.id = 'itemTemplate';
    t.innerHTML = this.innerHTML;
    
    this.list = [{name: 'Item 1', id: 'item1'},
                 {name: 'Item 2', id: 'item2'},
                 {name: 'Item 3', id: 'item3'}];
    
    this.shadowRoot.appendChild(t);
    

    演示:http://jsbin.com/IVodePuS/3/edit

    【讨论】:

    • 这正是我所缺少的。在我重新阅读了关于 shadow DOM subtrees 的文档之后,它肯定更有意义。非常感谢!
    • @ebdel 在 Polymer 1.2+ 中仍然可以实现这样的事情吗? stackoverflow.com/questions/34645114/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多