2016-10-12 26 views
-1

我正在第一次使用聚合物iron-ajax元素,並且遇到了一個我認爲相當簡單的問題,但我無法找到解決方案線上。
將鐵ajax請求中的返回值存儲在變量中(聚合物)

我用iron-ajax元素檢索用戶詳細信息,並用dom-repeat遍歷它。用戶的名字和姓氏被放置在我創建的自定義卡片元素中以顯示用戶。一切工作正常,但我無法將返回的id值存儲在變量中。 我相信這是可能的使用數據綁定,但我無法得到它的工作。即使當我嘗試在JavaScript中使用getAttribute獲取值時,它也會返回null。

在我下面的鐵Ajax請求&響應代碼可以包括我笨拙地企圖獲得的id值中找到{{item.id}}。要做到這一點我創建了一個上階的功能,當用戶點擊在其中一張卡上,然後應該得到stdId屬性的值。

<dom-module id="my-students-view"> 
<template> 

    <style> 
    :host { 
     display: block; 
    } 
    </style> 

    <!-- Iron-Ajax created connection and gets data --> 
    <iron-ajax 
    auto 
    id="requestRepos" 
    url="http://api.dev/user/" 
    handle-as="json" 
    loading="{{isloading}}" 
    last-response="{{response}}"></iron-ajax> 

    <!-- dom-repeat iterates the response --> 
    <template is="dom-repeat" items="[[response.data]]" sort="sortData"> 
    <student-card 
     id="studentCard" 
     to="http://localhost:8080/profile-view/{{item.id}}" 
     picsrc="../../images/anonymous.jpg" 
     name="{{item.first_name}} {{item.last_name}}" 
     stdId="{{item.id}}" 
     on-tap="sendId"></student-card> 

    </template> 
</template> 

<script> 
Polymer({ 
    is: 'my-students-view', 

    properties: { 
    stdId: { 
     notify: true, 
    } 
    }, 

    //Sort the array/data alphabetically 
    sortData: function(a, b) { 
    if(a.first_name < b.first_name) return -1; 
    if(a.first_name > b.first_name) return 1; 
    return 0; 
    }, 

    //Try to get the id value of a the student card 
    sendId: function() { 
    var idPropertie = this.$$("#studentCard"); 
    var idValue = idPropertie.getAttribute('stdId'); 
    console.log('the id is:' + idValue); 
    }, 

}); 

</script> 
</dom-module> 

回答

1

重寫sendId功能:

sendId: function(event) { 
    var idValue = event.model.item.id; 
    console.log('the id is:' + idValue); 
}, 
+0

非常感謝@Patricklaf! 是否有任何文檔解釋了爲什麼我只能通過 event.model訪問它? – Niklas

+1

文檔在這裏:https://www.polymer-project.org/1.0/docs/devguide/templates#handling-events – Patricklaf