简体   繁体   中英

UI not updating when sorting observable array in KnockoutJs

I am facing problem when i am sorting observable array, array gets updated but not changing UI

code:

Model code:

function OrderByOptionModel(field, displayText, isSelected, dispIndex) {
    var self = this;

    self.field = field;
    self.dispText = displayText;
    self.isSelected = ko.observable(isSelected);
    self.dispIndex = dispIndex;

    self.click = function (data) {
        if (data == null) return;
        data.isSelected(!data.isSelected());
    };

    self.getOrderByOptions = function () {
        return [
            new OrderByOptionModel(OrderByTypes.INDUSTRY, 'Industry', false, 1),
            new OrderByOptionModel(OrderByTypes.SUPERSECTOR, 'Super Sector', false, 2),
            new OrderByOptionModel(OrderByTypes.SECTOR, 'Sector', false, 3),
            new OrderByOptionModel(OrderByTypes.SUBSECTOR, 'Sub Sector', false, 4),
            new OrderByOptionModel(OrderByTypes.COUNTRY, 'Country', false, 5),
            new OrderByOptionModel(OrderByTypes.MARKETCAP, 'Market Cap', false, 6),
            new OrderByOptionModel(OrderByTypes.ATOZ, 'A - Z', false, 7),
            new OrderByOptionModel(OrderByTypes.DATETIME, 'Date Time', false, 8)
        ];
    };
    return self;
}

Observable Array:

self.orderByOptions = ko.observableArray(OrderByOptionModel().getOrderByOptions());

Sorting Code:

 self.orderByOptions().sort(function (l, r) {
             return l.dispIndex > r.dispIndex ? 1 : -1;
        });

But UI not gets updated i dont know where is the problem?

Remove the parenthesis in your observableArray assignment.

self.orderByOptions = ko.observableArray(OrderByOptionModel().getOrderByOptions);

The thing with knockout is it calls functions on your behalf when binding things to observables. Sometimes just removing the parenthesis to functions that return data and binding to the function itself fixes it.

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