Polymer中的数据绑定

时间:2016-11-11 08:56:27

标签: javascript json polymer

我有这个函数,在调用它时会给我一个JSON返回值。

getJSON function(url, success){
var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0]
               || document.documentElement;
        window[ud] = function(data) {
            head.removeChild(script);
            success && success(data);
        };
        script.src = url.replace('callback=?', 'callback=' + ud);
        head.appendChild(script);
}

要调用该函数,我使用以下代码。

getJSON('https://newsapi.org/v1/articles?source=techcrunch&apiKey={APIKEY}', function(data){
          //Stuff to be done with the data
        });

然后我有一张纸卡,我想要绑定我得到的JSON值。

<paper-card heading="Card Title">
      <div class="card-content">{{json}}</div>
</paper-card>

我想要做的是以聚合方式声明getJSON函数的调用,调用函数并将返回的JSON值设置为纸卡中的{{json}}数据元素。我已经尝试了超过5种方法来做上述事情,但我不能做我想做的事情。我是聚合物新手,请帮助我。

1 个答案:

答案 0 :(得分:3)

您可以使用Polymer的getJSON()元素为您提取数据,而不是编写自己的<iron-ajax>方法。

新闻API data看起来与此JSON对象类似:

{
  "status": "ok",
  "source": "the-next-web",
  "sortBy": "latest",
  "articles": [{
    "author": "TNW Deals",
    "title": "4 offers from TNW Deals you won’t want to miss",
    "description": "We’ve featured some great offers from TNW …",
  }, {
    "author": "Bryan Clark",
    "title": "Amazing 4k video of the Northern Lights",
    "description": "Tune in, and zone out …",
  }]
}

我假设您要显示articles[]数组中的每篇文章。

<iron-ajax>元素可以从新闻API请求数据并将服务器响应存储在lastResponse中,您可以绑定到可以在模板中使用的属性。

在以下示例中,我们看到last-response="{{data}}"<iron-ajax>会将新闻API响应输出到data(即,设置this.data = response,其中response是上面的JSON对象)。鉴于前面提到的数据的形状,我们知道data.articles将访问文章数组,这些文章可以传递给dom-repeat进行迭代:

<template>
  <iron-ajax url="https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=|APIKEY|" 
             auto
             last-response="{{data}}">
  </iron-ajax>

  <template is="dom-repeat" items="[[data.articles]]">
    <paper-card heading="[[item.title]]">
      <div class="card-content">
        <p>[[item.description]]</p>
      </div>
    </paper-card>
  </template>
</template>

或者,如果您需要事先强制操作响应,则setup an event listener事件可以<iron-ajax>.response。事件详细信息包含.response中的数据。您可以处理/修改该数据,并将结果分配给this.articles中绑定的dom-repeat

<template>
  <iron-ajax url="https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=|APIKEY|" 
             auto
             on-response="_onResponse">
  </iron-ajax>

  <template is="dom-repeat" items="[[articles]]">
    <paper-card heading="[[item.title]]">
      <div class="card-content">
        <p>[[item.description]]</p>
      </div>
    </paper-card>
  </template>
</template>

<script>
  Polymer({
    ...
    _onResponse: function(e) {
      var data = e.detail.response;
      // do something with data...

      // set this.articles for dom-repeat
      this.articles = data;
    }
  });
</script>