簡體   English   中英

在聚合物中的回調中設置數組項屬性值

[英]Setting Array Item Property Value in Callback in Polymer

我有一個使用Polymer的應用程序。 在此應用程序中,我將一系列項目綁定到UI。 用戶可以單擊一個按鈕。 單擊該按鈕時,將調用與第三方庫關聯的任務。 該任務完成后,將返回狀態。 我需要將該狀態綁定到數組中某個項目的屬性。 第三方庫允許我使用回調函數。 因此,我將使用setTimeout函數中setTimeout JavaScript演示我的挑戰。

my-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; 
            setTimeout(function() {
              this.set('items.1.status', 'In Stock');
            }, 1000);             
          }          
        });
    </script>
</dom-module>

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

item-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) {
                alert(newValue);
                if (newValue === 'In Stock') {
                  this.statusClass = 'green';
                } else if (newValue === 'Sold Out') {
                  this.statusClass = 'red';
                } else {
                  this.statusClass = 'black';
                }
            }
        });
  </script> 
</dom-module>

用戶單擊“綁定”按鈕時,狀態不會在UI中更新。 我注意到最初加載視圖時出現了為調試目的添加的alert 但是,單擊“綁定”按鈕時,不會出現alert窗口。 這意味着觀察者功能未觸發。 我的回調實際上看起來像這樣:

getStatus(1, function(status) {
  this.set('items.1.status', status);
}); 

如何通過回調設置數組項的屬性?

setTimeout有自己的范圍。 '.bind(this)'可用於將Polymer元素范圍綁定到回調函數。 下面的bindClick函數應該可以工作

      bindClick: function() {
        setTimeout(function() {
          this.set('items.1.status', 'In Stock');
        }.bind(this), 1000);
      }          

工作的jsbin: http ://jsbin.com/mehovu/edit?html,輸出

暫無
暫無

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

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