简体   繁体   中英

In Knockout.js, how to sort array

In the ViewModel i have an observableArray and a computed which return the array managed in the view:

var operators = ko.observableArray([]);
    var records = ko.computed(function () {
        return operators();
    });

This is my sort method;

Order = function (data, event, colName) {
            var th = $('#th-' + colName),
                attr = th.data('sort');

            setAttribute(th, attr); //switch data-sort between 'asc' and 'desc'

            if (attr === 'asc') {
                operators = operators.sort(function (a, b) {
                    return (a.fullname === b.fullname) ? 0 : (a.fullname < b.fullname ? -1 : 1);
                });
            }
            else {
                operators = operators.sort(function (a, b) {
                    return (a.fullname === b.fullname) ? 0 : (a.fullname > b.fullname ? -1 : 1);
                });
            }
        };

And this is the view:

<table id="table-hour">
    <thead>
        <tr>
            <th data-bind="click: function(data, event) { Order(data, event, 'fullname')}" data-sort="asc" id="th-fullname">Fullname</th>
        </tr>
    </thead>
    <tbody>
        <!-- ko foreach: records -->
        <tr>
            <td>
                <span data-bind="text: fullname"></span>
            </td>
        </tr>    
        <!-- /ko -->
    </tbody>

Well, the sort function work like a charm, in fact debugging with the browser i can see the array sorted in both ways, but the view is updated only the first time. What should I do to fix this problem?

The problem is, you need to update the observableArray, and put the data back in that array.

A view doesn't update, if the observable isn't updated

Take a look at the JavaScript sort functionality ( https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM