聚合物中的数据绑定

Data binding in Polymer

本文关键字:数据绑定 聚合物      更新时间:2023-09-26

我有这个函数,它在调用时给我一个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种以上的方法,但我不能做我想做的。我是聚合物新手,所以请帮助我。

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

新闻API数据看起来类似于这个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>元素可以从News API请求数据,并将服务器响应存储在lastResponse中,您可以将其绑定到可以在模板中使用的属性。

在下面的示例中,我们看到last-response="{{data}}", <iron-ajax>将把News 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>

或者,如果您需要事先强制操作响应,您可以为<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>