各家框架都有把列表資料綁定到 DOM 上的機制,Angular 用 ng-repeat,Polymer 則提供 dom-repeat。它並非獨立標籤,而是建立在 template 標籤之上的一種指令。
<script>
var Polymer = { dom: 'shadow' };
</script>
<base href="https://www.web-tinker.com/share/" />
<link rel="import" href="polymer/polymer.html" />
<dom-module id="demo-test">
<template>
<ul>
<template is="dom-repeat" items="[[data]]">
<li>
第 <strong>[[index]]</strong> 項,值為 <strong>[[item]]</strong>
</li>
</template>
</ul>
</template>
<script>
Polymer({
is: 'demo-test',
properties: {
data: {
type: Array,
value: ['a', 'b', 'c', 'd']
}
}
});
</script>
</dom-module>
<demo-test></demo-test>
對 template 加上 is="dom-repeat",其內部內容就會依 items 提供的陣列被重複渲染。每一項的索引與值會分別注入 index 與 item,供模板內使用。
值得稱道的是 items 必須是陣列。這看似不便,卻能有效避免 for-in 遍歷帶來的各種非預期屬性問題。
Polymer 的資料更新並非基於髒值比對,因此直接操作陣列不會觸發介面更新。
<dom-module id="demo-test">
<template>
<input placeholder="請輸入內容" value="{{value::input}}" />
<button on-click="append">添加一項</button>
<ul>
<template is="dom-repeat" items="[[data]]">
<li>
第 <strong>[[index]]</strong> 項,值為 <strong>[[item]]</strong>
</li>
</template>
</ul>
</template>
<script>
Polymer({
is: 'demo-test',
properties: {
data: { type: Array, value: ['a', 'b', 'c', 'd'] }
},
append: function () {
// data.push(this.value); 這樣寫不會生效
this.push('data', this.value);
}
});
</script>
</dom-module>
Polymer 會把需要監控的資料實作為存取器屬性。當你把一個陣列賦值給 VM 時,實際上是把元素複製過去,而非把陣列物件本身交出去。也就是說,你手上那個陣列並不是 VM 的參照,對它做 push 只會改動資料本身,VM 無從得知。
為此 Polymer 提供了一組直接操作 VM 的方法,例如範例中的 this.push。注意它的第一個參數不是物件,而是 VM 上的一條「存取路徑」:
this.push('data', newValue); // 在 data 路徑的陣列尾端追加
this.pop('data');
this.shift('data');
this.splice('data', index, 1);
這些方法對應原生陣列操作,但掛在元素上而非陣列上。寫起來確實不如原生順手,不過一旦理解「路徑」這個設計,就能準確控制何時觸發綁定更新。若是嵌套結構,路徑也可以寫成 'user.tags' 這樣的形式。