2015-10-20 87 views
0

我有一個使用聚合物的應用程序。在這個應用程序中,我將一組項目綁定到UI。用戶可以點擊一個按鈕。單擊該按鈕時,將調用與第三方庫關聯的任務。當該任務完成時,它返回一個狀態。我需要將該狀態綁定到我的數組中的項目的屬性。第三方庫允許我使用回調函數。出於這個原因,我會用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

項目,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); 
}); 

如何從回調中設置數組項的屬性?

回答

1

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,output

+0

'setTimeout'被用作一個使用回叫的東西的例子。這種方法是否適用於通常的回調?我用我的代碼嘗試了上面的方法,不幸的是,它沒有工作。 –

+0

我認爲應該。如果你可以在你的例子附近創建一個jsbin。那麼看看發生了什麼會很有幫助。 – Srik

+0

您提供的'bind'方法最終將1000作爲參數傳遞到回調函數中。我用一個更精確地表示如何設置我的函數調用的示例更新了示例。 –