子对象的KO映射问题 [英] KO Mapping issue with child objects
问题描述
我从服务器获取以下数据:
I get the following data from the server:
var data = [{ id: 0, child: { prop1 : 'a', prop2 : 'b' } } //Child object has data
,{ id: 0, child: null } ]; // Child object is null
使用敲除映射插件映射数据后,出现了一些问题.问题是内部child
对象不是同一类型.
I'm having some issues after I map the data using the knockout mapping plugin. The issue is that the inner child
object is not of the same type.
执行此操作后:
ko.mapping.fromJS(data, viewModel.data);
我发现第一个对象的数据具有Object
类型的child
属性.但是,第二个对象具有类型为Observable
的属性child
,在展开时,该属性将返回null.
I get that the first object has a child
property of type Object
with the data. However the second object has a property child
of type Observable
that when it's unwrapped returns null.
在两种情况下,即使一个对象具有值,而另一个对象为null,如何使它们具有相同的类型.更改服务器的行为方式不是一种选择.我希望同时具有Object
和null
或同时具有Observables
.
How can I make that in both cases the objects have the same type even one has value and the other one is null. Changing the way the server behaves is not an option. I expect having Object
and null
or both Observables
.
JsFiddle 此处.
JsFiddle here.
推荐答案
您需要使用 create
选项告诉映射插件它应该如何映射您的child
属性.
因此,如果要拥有Object
和null
,则需要在子属性为null
时返回null
:
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);
演示 JSFiddle .
或者如果您想同时使用它们Observables
:
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);
这篇关于子对象的KO映射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!