は、以下のコードを考えてみましょう:ポリマーバインディングはどのようにアレイ上で機能しますか?
<dom-module id="foo-bar">
<template>
<h2>Example 1</h2>
<button on-tap="tap1">Tap 1</button> | <button on-tap="tap2">Tap 2</button>
<hr>
<ul>
<template is="dom-repeat" items="{{myarray}}">
<li>{{index}}: {{item.title}}</li>
</template>
</ul>
<hr>
{{myarray}}
<hr>
<h2>Example 1</h2>
<button on-tap="tap3">Tap 3</button>
<hr>
<ul>
<template is="dom-repeat" items="{{myarray2}}">
<li>{{index}}: {{item.title}}</li>
</template>
</ul>
<hr>
{{myarray2}}
<hr>
</template>
<script>
Polymer({
is: 'foo-bar',
properties: {
myarray: {
type: Array,
value: [null, null],
notify: true
},
myarray2: {
type: Array,
value: [{title: 'a'}, {title: 'b'}],
notify: true
}
},
tap1: function() {
this.myarray = [{title: 'Hello'}, {title: 'World'}];
},
tap2: function() {
this.set('myarray.0', {title: 'Hello'});
this.set('myarray.1', {title: 'World'});
},
tap3: function() {
this.set('myarray2.0', {title: 'Hello'});
this.set('myarray2.1', {title: 'World'});
}
})
</script>
</dom-module>
原理は、アレイ(myarray
)の内容を表示することで、いつでもその内容の変更、表示を更新します。
Tap 1
ボタンをクリックすると、配列が完全に再定義されるため、すべて正常に動作します。
documentationによれば、ポリマーはアレイ自体の中で修飾を検出することができず、this.set(...)
方法の使用を推奨している。それは私が私のコードのtap2
機能にやったことだ:
tap2: function() {
this.set('myarray.0', {title: 'Hello'});
this.set('myarray.1', {title: 'World'});
}
しかし、私は、配列が正しくコード内で更新された場合でも、Tap 2
ボタンをクリックしたときに(私はconsole.log
でそれを見ることができます)、
- 0:世界
- 1:私が得るとして(
<ul></ul>
中)リストには、正しく設定されていない
(最初のインデックスはアレイの2番目の要素の値を表示します)、配列のフルディスプレイ({{myarray}}
)は何も印刷しません。
もう1つのシナリオTap3
は、オブジェクトで直接配列(myarray2
)を初期化しているため、正しく動作します。
また、私はが[]
であり、[null, null]
ではなく、初期化されている別のテストを行っています(Plunkerではなく)。その場合、ボタンをクリックする前または後に、リスト(<ul></ul>
)は常に空です。
最後に、私の質問は、配列の内容に二重バインディングがどのように作用するのか、なぜ二番目のケース(Tap 2
)が起こるのかを理解することです。問題はdom-repeat
は、非ユニークなプリミティブに問題があるということです
おかげ