我在页面上有多个iron-ajax标签,例如:
<iron-ajax
auto
id="ajaxCall1"
url="/data/test1.json"
handle-as="json"
on-response="_myAjaxCall1ResponseHandler"
last-response="{{_myAjaxCall1LastResponse}}"
debounce-duration="300">
</iron-ajax>
<iron-ajax
auto
id="ajaxCall2"
url="/data/test2.json"
handle-as="json"
on-response="_myAjaxCall2ResponseHandler"
last-response="{{_myAjaxCall2LastResponse}}"
debounce-duration="300">
</iron-ajax>
在进行其他操作之前,如何等待两个请求完成?我不关心请求的顺序,只是他们已经完成了。
感谢。
答案 0 :(得分:4)
观察多个属性仅在both become defined时触发观察者。因此,如果您观察到绑定到last-response
的两个响应,则只有在两个请求都完成后才会触发。
Polymer({
observers: [
'_requestsFinished(_myAjaxCall1LastResponse, _myAjaxCall2LastResponse)'
],
_requestsFinished: function(res1, res2) {
// will only fire when res1 and res2 are non-undefined
}
});
诀窍是在再次触发请求之前取消设置属性,以便观察者等待再次定义两者。请参阅下面的代码段。
Polymer({
is: 'my-elem',
properties: {
prop1: Object,
prop2: Object,
observer: {
value: 'not fired'
}
},
observers: [
'observeBoth(prop1, prop2)'
],
observeBoth: function(prop1, prop2) {
console.log('observer');
this.observer = 'fired';
},
set1: function() {
console.log('prop1');
this.prop1 = 'x';
},
set2: function() {
console.log('prop2');
this.prop2 = 'x';
},
unset: function() {
this.prop1 = undefined;
this.prop2 = undefined;
this.observer = 'not fired';
}
});
&#13;
<!DOCTYPE html>
<html>
<head>
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import"/>
</head>
<body>
<my-elem></my-elem>
<dom-module id="my-elem">
<template>
Observer: {{observer}}
<br>
<input type="button" value="set prop1" on-tap="set1" />
<input type="button" value="set prop2" on-tap="set2" />
<input type="button" value="unset props" on-tap="unset" />
</template>
</dom-module>
</body>
</html>
&#13;