简体   繁体   中英

Manually update knockout observableArray

I have an observable Array being populated by an AJAX call but it is not updating.

function ViewModel() {
    var self = this;
    self.FinanceTypes = ko.observableArray([]);
    self.Country = ko.observable('@Model.Country.CountryName');

    function FinanceTypeViewModel(data) {
        var self = this;
        self.Name = data.Name;
        self.Tax = data.TaxPercentage;
        //self.Accounts = data.AccountTypes;
    }

    self.getFinanceTypes = function() {
        var data = { country: ko.toJS(self.Country()) };

        $.getJSON("/Admin/GetFinanceTypes", data, function(result) {
            var mapped = ko.utils.arrayMap(result, function(item) {
                return new FinanceTypeViewModel(item);
            });
            ko.utils.arrayPushAll(self.FinanceTypes(), mapped);
            self.FinanceTypes.valueHasMutated();
        });
    }

    self.getFinanceTypes();
}

The problem line is

self.FinanceTypes.valueHasMutated();

everything else works. This gives an "Uncaught ReferenceError: Name is not defined"

If I change it to

self.FinanceTypes().valueHasMutated();

I get "Uncaught TypeError: undefined is not a function"

Thanks

Calling ko.utils.arrayPushAll(self.FinanceTypes(), mapped) pushes all the items in mapped into the unwrapped FinanceTypes . Call it without unwrapping it and you won't have to call valueHasMutated : ko.utils.arrayPushAll(self.FinanceTypes, mapped)

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