简体   繁体   中英

KnockoutJs bind JSON obj to nested ViewModel and dont ignore ViewModel not corresponding properties to JSON obj and keep VM functions

I define a nested viewmodel in KnockoutJs, Like this:

function Person() {
    var self = this;
    self.title = ko.observable("");
    self.someProp = ko.observable(false);
    self.someFunc = function() {
        self.someProp(false);
    };    
}

function viewModel() {
    var self = this;

    self.someData = ko.observableArray([new Person()]);

    self.loadPersonsData = function() {
        $.ajax({
            type: "POST",
            url: '/GetAllPersons',
            dataType: "json",
            async: false,
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({"catId": selectedCategoryId }),
            success: function (response) {
                self.someData(response.someData);                                       
            }
    });
}

Required data get from ajax, then title property of Person fill from JSON object, but someProp property dont exist in JSON object returned from server. And then apply bindings :

var vm;
$(function() {
    vm = new viewModel();    
    vm.loadPersonsData();    
    ko.applyBindings(vm);
});

Binding view to html elements in this way:

<section data-bind="foreach: someData">
    .
    .
    .
    <button data-bind="click: function(data, event) {  $data.someFunc(); event.stopPropagation(); }" type="button">other</button>
</section>

When click to button the below error message was shown:

TypeError: $data.someFunc is not a function

Then i change codes before apply bindings:

vm = new viewModel();    
vm.loadPersonsData();
$.each(vm.someData() , function(i, val) {         
    self.someProp = ko.observable(false);
    self.someFunc = function() {
        self.someProp(false);
    };    
});
ko.applyBindings(vm);

By using this code top error not shown and app work fine. by calling vm.loadPersonsData(); in another function or event, data successfully get from server and bind to html. But by clicking on the button top error message was shown.

Please tell me that how to fix this bug? regards

Your callback

success: function (response) {
    self.someData(response.someData);                                       
}

isn't inflating Person objects, it's appending the data, not an instance of Person

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