KO Mapping issue with child objects

自闭症网瘾萝莉.ら 提交于 2019-12-05 03:30:41
nemesv

You need to use the create option to tell the mapping plugin how it should map your child property.

So if you want to have having Object and null you need to return null when your child property is null:

var mappingOptions = {
    child: {
        create: function(options) {
            if (!options.data)
                return null;
            return ko.mapping.fromJS(options.data);
        }
    }
}

ko.mapping.fromJS(data, mappingOptions, viewModel.data);  

Demo JSFiddle.

Or if you want them both Observables:

var mappingOptions = {
    child: {
        create: function(options) {
            return ko.observable(ko.mapping.fromJS(options.data));
        }
    }
}

ko.mapping.fromJS(data, mappingOptions, viewModel.data);   

As mentioned, the solution is mapping options, but make sure to always test the options.data for null value and then return empty ko.observable(), otherwise you are going to have a lot of trouble with binding! I spent a lot of time on finding that.

var mappingOptions = {
    child: {
        create: function (options) {
            return options.data != null ? ko.observable(ko.mapping.fromJS(options.data)) : ko.observable();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!