Sorting an Observable Array in Knockout

后端 未结 4 851
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 12:13

I have an observable array in Knockout of person objects. I wanted to be able to sort the list of persons based on the last name. The problem is the list has a number of duplica

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 13:08

    I had some issues trying to sort a observable array, I was not seeing any results in my code.

    You need to sort the results you receive via ajax/getJSON request first, before you return the new items into your array.

    This way the results are sorted before they are added into your observable array as new items. No need to sort them at the bindings then.

    See the example below.

    players(ko.utils.arrayMap(result, function (item) {
                        result.sort(function (l, r) {
                            return l.name == r.name ? 0 : (l.name < r.name ? -1 : 1);
                        });
                    return new Player(item);
                }));
    
    1. get data using AJAX / getJSON
    2. Sort the result of that request into your array of choice

提交回复
热议问题