假设我有一个只有id的对象数组:
[{id:'1'},{id:'2'},{id:'3'}]
我希望使用iron-ajax逐个填充来自某些服务的数据:
<iron-ajax id="initObjectByIdService"
handle-as="json"
on-response="_handleResponse"></iron-ajax>
...
initObjects: function(){
for (var i =0; i < arr.lenght; i++){
this.$.initObjectByIdService.url = <some_url> + '/' + arr[i].id
this.$.initObjectByIdService.generateRequest();
}
},
_handleResponse: function(event){
// How I can link this response event with proper element of an array?
}
可能有用的是将调用者的元素索引传递给on-response
函数,如:
...
this.$.initObjectByIdService.onResponse = this._handleResponse(i);
...
但它看起来很奇怪而且不对,并且不起作用...... :(
答案 0 :(得分:1)
您应该可以使用 let 关键字解决此问题,如下所示:
initObjects: function() {
// using let instead of var
for (let i =0; i < arr.lenght; i++){
this.$.initObjectByIdService.url = <some_url> + '/' + arr[i].id
var request = this.$.initObjectByIdService.generateRequest();
request.completes.then(function(response) {
// your i variable should be available in this block
});
}
},
不需要 let 关键字的解决方案可能如下所示:
initObjects: function() {
// using let instead of var
for (var i =0; i < arr.lenght; i++){
this.$.initObjectByIdService.url = <some_url> + '/' + arr[i].id
var request = this.$.initObjectByIdService.generateRequest();
request.completes.then(this._handleResponse(i));
}
},
_handleResponse: function(i) {
return function(response) {
// i variable should be normally visible in this scope
};
}
在这两种情况下,您还应该从 iron-ajax 组件中删除响应时属性。