0
我想實現一個包含紙張選項卡的頁面,每個選項卡根據名稱初始值顯示一個項目列表。我想知道數據綁定的最佳方式是什麼。聚合物數據綁定:如何訪問嵌套模板中的數據?
另外我有一些麻煩訪問嵌套模板中的數據。當我點擊不同的標籤時,它不像我預期的那樣工作。
下面是簡化的代碼:
//page
<paper-tabs selected="{{tab}}">
<template repeat="{{inital in pagination}}">
<paper-tab name="{{initial}}">
{{initial}}
</paper-tab>
</template>
</paper-tabs>
<items-field
tab="{{tab}}"
items="{{items}}">
</items-field>
//items-field
<polymer-element name="items-field" attributes="tab items">
<template>
<h2>h2 {{tab}}</h2>
<div>some other stuffs</div>
<template bind="{{items}}">
<h3>h3 {{tab}}</h3> <-- {{tab}} is undefined
<item-list
initial="{{tab}}"
</item-list>
</template>
</template>
<script>
Polymer({
tab: 'A'
)}
</script>
</polymer-element>
//item-list
<polymer-element name="items-list" attributes="initial">
<template>
<template repeat="{{item in items}}">
<item
hidden?="{{toHide(initial, item.name)}}">
</item>
</template>
</template>
<script>
Polymer({
ready: function() {
this.items = this.templateInstance.model;
console.log(this.initial); // <-- undefined
},
toHide: function (initial, name) {
if (initial === undefined ||
initial === name.charAt(0)) {
return false;
}
return true;
}
});
</script>
</polymer-element>
感謝@robdodson!我喜歡「元素就是模型」的想法。我的理解是:當我使用「綁定」時,該元素就是該模型;當我使用「屬性」時,我向模型中注入了一些東西。最佳做法是什麼,使用「綁定」還是使用「屬性」? – DrXCheng 2015-02-24 20:08:55
綁定主要用於創建模板範圍,並且,正如我所看到的那樣,只是在鍵入時節省了時間。我會盡可能地讓儘可能多的組件無狀態和愚蠢。然後通過屬性綁定將數據流向它們。 – robdodson 2015-02-24 22:27:02