我希望在一个铁列表中对数据进行排序(以及在数据数组中添加项时对它们进行排序)。
示例(未排序) json数据:
[
{"name": "Zebra"},
{"name": "Alligator"},
{"name": "Lion"}
]我尝试使用indexAs属性对iron-list进行排序,如下所示,但是API接口不清楚如何使用它:
<iron-ajax url="./data.json" last-response="{{data}}" auto></iron-ajax>
<iron-list items="[[data]]" as="item" index-as="name" class="fit">
<template>
<div>
Name: <span>[[item.name]]</span>
</div>
</template>
</iron-list>发布于 2015-08-14 14:23:55
我不太确定是否有更多的天然聚合物方法来做到这一点,但是自己构建排序逻辑并不太复杂。
其想法是侦听response事件,对服务中的数据进行排序,然后将iron-list的items绑定到sortedData。
您需要将on-response="_onResponseReceived"添加到iron-ajax中。然后只需要对返回的数据进行排序。
_onResponseReceived: function () {
this.sortedData = this.data.sort(this._compare);
},
_compare: function (a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}当然,iron-list现在需要更新为
<iron-list items="[[sortedData]]" ...>发布于 2016-02-11 01:36:42
使用Polymer1.2.4,如果您想以动态的方式对iron-list进行排序,您还可以利用this.querySelector('iron-list').notifyResize();在您的观察者中更新sortedItems数组之后强制进行刷新。这是一个黑客,但如果你不这样做,不幸的聚合物不会刷新名单为你。让我们按id或name对项目进行排序:
<template>
<paper-icon-button icon="expand-more" on-tap="_sortItems" sort-option="id"></paper-icon-button>
<paper-icon-button icon="expand-more" on-tap="_sortItems" sort-option="name"></paper-icon-button>
<iron-list items="[[sortedItems]]">
<template>
<p>[[item.name]]<p>
</template>
</iron-list>
</template>
...
properties: {
...
sortByTerm: {
type: String,
value: 'id'
},
sortByOrder: {
type: Number,
value: -1 // Descending order
},
},
observers: [
'sortingObserver(items.*, sortByTerm, sortByOrder)'
],
sortingObserver: function(items, sortByTerm, sortByOrder) {
var sortedItems = [],
validSortingOptions = ['id', 'name'];
if (validSortingOptions.indexOf(sortByTerm) != -1) {
sortedItems = items.base.sort(this._computeSort(sortByTerm, sortByOrder));
} else {
sortedItems = items.base;
}
this.set('sortedItems', sortedItems);
this.querySelector('iron-list').notifyResize();
},
_computeSort: function(property, order) {
return function(a, b) {
if (a[property] === b[property]) {
return 0;
}
return (order * (a[property] > b[property] ? 1 : -1));
};
},
_sortItems: function(e) {
var sortByTerm = e.currentTarget.getAttribute('sort-option');
this.set('sortByTerm', sortByTerm);
},
...https://stackoverflow.com/questions/32009715
复制相似问题