我是使用iron-ajax的用户铁列表,但是在将元素推送到铁列表给出null异常之后的ajax响应=“无法读取未定义的属性'_list'”
<script>
Polymer({
is: 'my-home',
ready: function () {
this.$._ajax.generateRequest();
},
onResponse: function (e) {
var people = e.detail.response.data;
people.forEach(function (person) {
this.$._list.push('items', person);
});
// Clear the lower threshold so we can load more data when the user scrolls down again.
this._scrollTheshold.clearTriggers();
}
});
</script>
这是我的铁列表的HTML代码
<iron-list id="_list" items="[[data.data]]" as="item">
<template>
<div style="margin-top: 0px">
<!--Card with header image http://placehold.it/350x150/FFC107/000000-->
<paper-card>
<div class="card-content">
<h1 class="feed_title">[[item.heading]]</h1>
<p class="feed_description">[[item.subheading]]</p>
</div>
<div class="card-actions">
<paper-button class="button-blue">
Share
</paper-button>
<paper-button class="button-blue">
Explore
</paper-button>
</div>
</paper-card>
</div>
</template>
</iron-list>
答案 0 :(得分:1)
在forEach()
函数表达式中,this
引用Window
对象,而不是Polymer对象。 (如果在此使用"use strict"
,this
将为undefined
,但似乎情况并非如此。)
解决此问题的几个选项:
选项1:使用ES6 arrow function,它不绑定自己的this
(假设ES6可用):
onResponse: function (e) {
var people = e.detail.response.data;
people.forEach(person => {
this.$._list.push('items', person);
});
...
}
选项2:使用ES6 for-of
loop,无需回拨(假设ES6可用):
onResponse: function (e) {
var people = e.detail.response.data;
for (const person of people) {
this.$._list.push('items', person);
});
...
}
选项3:使用ES6 spread operator一次推送所有数组项(假设ES6可用):
onResponse: function (e) {
var people = e.detail.response.data;
this.$._list.push('items', ...people);
...
}
选项4:传递对Polymer对象的引用:
onResponse: function (e) {
var self = this;
var people = e.detail.response.data;
people.forEach(function (person) {
self.$._list.push('items', person);
});
...
}
选项5:传入对列表对象的引用:
onResponse: function (e) {
var list = this.$._list;
var people = e.detail.response.data;
people.forEach(function (person) {
list.push('items', person);
});
...
}
选项6:在函数表达式中明确绑定this
:
onResponse: function (e) {
var people = e.detail.response.data;
people.forEach(function (person) {
this.$._list.push('items', person);
}.bind(this));
...
}
选项7:将this
作为forEach()
的第二个参数:
onResponse: function (e) {
var people = e.detail.response.data;
people.forEach(function (person) {
this.$._list.push('items', person);
}, this);
...
}
答案 1 :(得分:1)
添加到@ tony19&#39的答案,您也可以使用bind
people.forEach(function (person) {
this.$._list.push('items', person);
}.bind(this));