2015-10-20 19 views
0

我有一個使用聚合物的應用程序。在這種應用中,我有一個看起來像這樣的組件:以編程方式設置聚合物中數組項目的屬性值

我-component.html

<dom-module id="view-tests"> 
    <template> 
     <table> 
     <tbody> 
      <template is="dom-repeat" items="{{ items }}" as="item">    
       <tr> 
       <td>[[ item.name ]]</td> 
       <td><item-status status="[[ item.status ]]"></item-status></td> 
       </tr> 
      </template> 
     </tbody> 
     </table> 

     <button on-click="bindClick">Bind</button> 
    </template> 

    <script> 
     Polymer({ 
      is: "my-component", 
      properties: { 
      items: { 
       type: Array, 
       notify: true, 
       value: function() { 
       return [ 
        new Item({ name:'Item 1', status:'In Stock' }), 
        new Item({ name:'Item 2', status:'Sold Out' }) 
       ]; 
       } 
      }, 
      }, 

      bindClick: function() { 
      var items = items;    
      for (var i=0; i<items.length; i++) { 
       if (i === 1) { 
       items[i].status = 'In Stock'; 
       } 
      } 
      }   
     }); 
    </script> 
</dom-module> 

如代碼片段所示以上,還有另外一個組件item-status

項-status.html

<dom-module id="test-status"> 
    <template> 
     <span class$="{{ statusClass }}">{{ status }}</span> 
    </template> 

    <script> 
     Polymer({ 
      is: "item-status", 
      properties: { 
       status: { 
        type: String, 
        value: '', 
        observer: '_statusChanged' 
       }    
      }, 

      _statusChanged: function(newValue, oldValue) { 
       if (newValue === 'In Stock') { 
        this.statusClass = 'green'; 
       } else if (newValue === 'Sold Out') { 
        this.statusClass = 'red'; 
       } else { 
        this.statusClass = 'black'; 
       } 
      } 
     }); 
    </script> 
</dom-module> 

初始數據綁定正常工作。但是,當我點擊「綁定」按鈕時,文本不會像我所期望的那樣更新。另外,文字顏色不會像我期待的那樣改變。我有意識地使用了var items = items;,因爲在我的真實代碼中,發生了回調,我必須將項傳遞給回調。我不確定是否有更好的方法。不過,我的觀點並沒有正確更新。

感謝您提供任何幫助。

回答

0
  1. 當我點擊「綁定」按鈕,文本不更新,我會想到

對於這個工作,你必須使用this.set('項目。 1.status','庫存')。有關數組綁定的更多詳細信息,請閱讀https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#array-binding

  1. 此外,文本顏色不會像我期待的那樣改變。

你只是設置類。您必須對項目進行設計。包括樣式標籤在您的項目狀態如下

<style> 
     .red { 
     color: red; 
     } 
     .green { 
     color: green; 
     } 
</style> 

3.我有VAR項目=項目;故意因爲在我的真實代碼中,有回調發生

我不認爲你可以在回調中設置數組項的值,並使聚合物觀察員工作。如果您在自己的場景中發佈更多細節,有人可能會幫助您。

  1. 這是一個很好的做法,讓你的dom模塊id和你的Polymer'是'id相同。這是我遇到不同ID的第一例,我幾乎肯定它會破壞某些東西。

工作jsbin:http://jsbin.com/yugofo/edit?html,console,output

相關問題