簡體   English   中英

數據綁定到聚合物中的數組

[英]Data Binding to Array in Polymer

我正在學習Polymer 我正在嘗試將數組綁定到我的UI。 數組中的每個對象都有一個將改變的屬性。 屬性值更改時,我需要更新UI。 我將聚合物成分定義如下:

我-component.html

<dom-module id="my-component">
    <template>
      <h1>Hello</h1>
      <h2>{{items.length}}</h2>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Status</th>
          </tr>
        </thead>

        <tbody>
          <tr repeat="{{ item in items }}">
            <td>{{ item.name }}</td>
            <td>{{ item.status }}</td>
          </tr>
        </tbody>
      </table>

      <br />

      <button on-click="testClick">Test</button>
    </template>

    <script>
        // element registration
        Polymer({
            is: "my-component",
            properties: {
                items: {
                  type: Array,
                  value: function() {
                      return [
                        new Item({ name:'Tennis Balls', status:'Ordered' }),
                        new Item({ name:'T-Shirts', status: 'Ordered' })
                      ];
                  }  
                }                
            },

          testClick: function() {
            for (var i=0; i<items.length; i++) {
              if (items.name === 'Tennis Balls') {
                items[i].status = 'Shipped';
                break;
              }
            }                  
          }
        });
  </script> 
</dom-module>

組件渲染。 但是,綁定根本不起作用。

  1. 帶有{{ items.length }}的行不顯示計數。 它基本上只是一個空的h2元素。
  2. 第一項在列表中呈現。 但是,第二個沒有。
  3. 當我單擊“測試”按鈕時,狀態更新不會顯示在屏幕上。

當我看一切時,對我來說看起來是正確的。 但是,從行為可以明顯看出,數據綁定設置不正確。 我究竟做錯了什么? 我真的感到困惑,即items.length和數組中所有項目的初始呈現。

聚合物數據綁定系統的工作方式如下:

如果聲明的屬性發生更改(例如添加新項),它將檢測到更改並更新您的DOM。

但是,Polymer不會監視物業內部的更改(出於性能/兼容性的原因)。

您需要通知Polymer屬性中的某些內容已更改。 您可以使用set方法或notifyPath做到這一點

例如(來自聚合物數據綁定部分

this.set('myArray.1.name', 'Rupert');

如果要在更新數組時執行某些操作,也可以添加觀察者。

聚合物1.0特性文檔

而且我認為您還應該在您的媒體資源中添加一個notify:true

items: {
              type: Array,
              notify:true,
              value: function() {
                  return [
                    new Item({ name:'Tennis Balls', status:'Ordered' }),
                    new Item({ name:'T-Shirts', status: 'Ordered' })
                  ];
              }  
            }             

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM