How to sort an iron-list in Polymer 1.0?

前端 未结 2 1445
渐次进展
渐次进展 2021-01-06 07:32

I am looking to sort data in an iron-list (and also sort items as they are added into the data array).

Sample (unsorted) json data:

[
  {\"name\": \"         


        
2条回答
  •  再見小時候
    2021-01-06 07:52

    With Polymer 1.2.4 if you want to sort an iron-list in a dynamic fashion you can also take advantage of this.querySelector('iron-list').notifyResize(); to force a refresh after you update the sortedItems array in your observer. This is a hack but if you don't do this unfortunately polymer doesn't refresh the list for you. Let's sort by id or name our items:

    
    ...
    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);
    },
    ...
    

提交回复
热议问题