聚合物铁-ajax间隔调用

时间:2016-05-26 11:43:58

标签: 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}}">

ajax在启动时被调用并运行。每当我使用其他铁ajax进行POST时,我都会调用this.$.getAjax.generateRequest();并且它可以正常工作。

问题是,如何使用某种计时器调用此函数。这里的想法是&#34;刷新&#34;使用iron-ajax的页面。 我在how to do it on JQuery上看到了一些答案,但我对Polymers属性vs函数与内部函数与此相比感到困惑。$ etc。

1 个答案:

答案 0 :(得分:9)

您将使用Polymer的method方法,如docs中所述:

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

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

  •   

以下示例定义了在{2}之后异步重新发送AJAX请求的on-response。这可以在<iron-ajax>的{​​{1}}处理程序内调用,以便在每次响应后2秒重新发送请求。

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

这是一个有效的演示:

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

jsbin

相关问题