聚合物中的数据绑定
Data binding in 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种以上的方法,但我不能做我想做的。我是聚合物新手,所以请帮助我。
您可以使用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>
相关文章:
- 聚合物 - 在重复模板中获取数据绑定属性值
- 聚合物数据绑定:如何访问嵌套模板中的数据
- 聚合物数据绑定铁 AJAX 并在控制台中访问获取的 JSON
- 聚合物重复模板双向数据绑定
- 聚合物 1.x:数据绑定阵列
- 聚合物将数据绑定到加载了 innerHTML 的元素
- 聚合物.js嵌套组件中的数据绑定
- 用于模板数据绑定的聚合物回调
- 将数据绑定到聚合物中的内容元素
- 聚合物:与简单数据绑定相比;t在第二个元素中起作用
- 聚合物网络组件数据绑定一个js对象/数组
- 聚合物中数据绑定到阵列
- 同步聚合物1.0元素之间的数据绑定
- 聚合物中的数据绑定
- 聚合物,在构造函数中使用属性数据绑定
- 聚合物属性没有通过数据绑定更新
- 使用数据绑定的聚合物芯-支架变更工具
- 在聚合物中注入html,包括数据绑定
- 聚合物+需求:在聚合物升级元素之前,对属性进行数据绑定
- 聚合物使用阵列进行数据绑定