如何将聚合物自定义元素绑定到内容? [英] how to bind polymer custom element to the contents?
问题描述
我正在尝试创建一个元素,该元素具有动态数量的选项卡,具体取决于为该元素提供的内容.我弄清楚如何做到这一点的唯一方法是在JS中,但我感觉这不是Polymer方法,我想念的是什么?您能否指出一些可以帮助我入门的文档或其他元素?
I'm trying to create an element which has a dynamic number of tabs depending on what content is given to the element. The only way I've figured out how to do this is in JS but I have a feeling this isn't the Polymer way, what am I missing? Can you point me to some docs or other elements that will help me get started?
这是我到目前为止所拥有的:
here's what I have so far:
使用我的自定义元素
<code-file-set>
<a href="#" tabTitle="onelink">onelink</a>
<a href="#" tabTitle="twolink">twolink</a>
<a href="#" tabTitle="threelink">threelink</a>
</code-file-set>
我的自定义元素的实现
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/core-pages/core-pages.html">
<link rel="import" href="/bower_components/paper-tabs/paper-tabs.html">
<polymer-element name="code-file-set">
<template>
<paper-tabs id="tabs" selected={{selected}}>
</paper-tabs>
<core-pages selected="{{selected}}">
<content id="codecontent" select="a"></content>
</core-pages>
</template>
<script>
Polymer('code-file-set', {
domReady: function() {
var codeNodes = this.$.codecontent.getDistributedNodes();
for (var i = 0; i < codeNodes.length; i++) {
var name = codeNodes[i].getAttribute('tabTitle');
var tab = document.createElement('paper-tab');
tab.innerHTML = name;
this.$.tabs.appendChild(tab);
}
this.selected = 0;
},
});
</script>
</polymer-element>
这有效,但是看起来很丑.即,不能在JS中创建选项卡,而是在HTML中以更具声明性的方式创建(请注意,我为内容中的每个元素创建了一个选项卡).
This works, but it seems ugly. Namely, can creating the tabs not be done in JS but in a more declarative way in the HTML (notice that I create one tab per element found in the content).
推荐答案
A proper data binding solution would be to define an array (tabs
) as a published property and use template repeat
to iterate through the array and populate each item onto the UI.
<polymer-element name="code-file-set" attributes="tabs">
<template>
<paper-tabs style="background-color:limegreen" selected="0">
<template repeat="{{tab in tabs}}">
<paper-tab>
<a href="{{tab.link}}">{{tab.tabTitle}}</a>
</paper-tab>
</template>
</paper-tabs>
</template>
<script>
Polymer('code-file-set', {
ready: function () {
this.tabs = [];
for (var i = 0; i <= 3; i++) {
this.tabs.push({ link: '#', tabTitle: 'title ' + i });
}
},
});
</script>
</polymer-element>
请参见此 jsbin 作为工作示例.
See this jsbin as a working example.
这篇关于如何将聚合物自定义元素绑定到内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!