0

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?

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you're right. I was doing it in the wrong way. Instead of operators = operators.sort(...) it's sufficient to call the sort utility on the observableArray: if (attr === 'asc') { operators.sort(function (a, b) {...}); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.