聚合物铁-ajax间隔调用

Mat*_*ter 1 javascript ajax polymer polymer-1.0

我有一个简单的聚合物前端应用程序.在其中,我有简单的ajax从后端获取数据:

<iron-ajax id="getAjax"
  auto
  url="http://localhost:14039/InvoiceService/envelop/{{envelopId}}/invoices"
  handle-as="json"
  last-response="{{invoices}}">
Run Code Online (Sandbox Code Playgroud)

ajax在启动时被调用并运行.每当我使用其他铁阿贾克斯进行POST时,我都会打电话给this.$.getAjax.generateRequest();它.

问题是,如何使用某种计时器调用此函数.这里的想法是使用iron-ajax"刷新"页面.我看到了关于如何在JQuery做到这一点的一些答案,但我对Polymers属性vs函数与内部函数与此相比感到困惑.$等.

ton*_*y19 9

您将使用Polymer的async()方法,如文档中所述:

  • async(method, [wait]).method异步调用.如果未指定等待时间,则运行具有微任务计时的任务(在当前方法完成之后,但在处理事件队列中的下一个事件之前).返回可用于取消任务的句柄.

  • cancelAsync(handle).取消已识别的异步任务.

以下示例定义_updateData()在2秒后异步重新发送AJAX请求.这可以在on-response处理程序内部调用,<iron-ajax>以便在每次响应后2秒重新发送请求.

Polymer({
  is: 'x-foo',
  _updateData: function() {
    this.async(function() {
      this.$.ajax.generateRequest();
    }, 2000);
  },
  _onResponse: function() {
    this._updateData();
  }
});
Run Code Online (Sandbox Code Playgroud)

这是一个有效的演示:

<head>
  <base href="https://polygit.org/polymer+1.11.1/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-ajax/iron-ajax.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <iron-ajax id="ajax"
                 auto
                 url="//jsonplaceholder.typicode.com/users/"
                 last-response="{{data}}"
                 on-response="_onResponse"
                 handleAs="json">
      </iron-ajax>
      <table>
        <template is="dom-repeat" items="[[data]]">
          <tr>
            <td>[[item.id]]</td>
            <td>[[item.name]]</td>
            <td>[[item.email]]</td>
          </tr>
        </template>
      </table>
      <div>
        <sup>See console log</sup>
      </div>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({
          is: 'x-foo',
          _updateData: function() {
            this.async(function() {
              this.$.ajax.generateRequest();
            }, 2000);
          },
          _onResponse: function() {
            console.log('received response');
            this._updateData();
          }
        });
      });
    </script>
  </dom-module>
</body>
Run Code Online (Sandbox Code Playgroud)

jsbin