2016-08-25 25 views
0

は、以下のコードを考えてみましょう:ポリマーバインディングはどのようにアレイ上で機能しますか?

<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は、非ユニークなプリミティブに問題があるということです

おかげ

Plunker link

答えて

1

(このissueを参照してください)。要素は一意の識別情報を持つ必要があります。回避策として、このようなあなたの配列を定義します。

myarray: { 
    type: Array, 
    value: function() { return [{}, {}];}, 
    notify: true 
}, 

これは、問題を修正します追記として

plunkerを変更参照):ArraysObjectプロパティの場合、デフォルト値を返すようにfunctionを使用することを確認してくださいvalueそれ以外の場合は問題に遭遇します(基本的にその要素のすべてのインスタンス間で値を共有します)

関連する問題