KO Matching 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 

I am having some problems after matching data using a knockout display plugin. The problem is that the inner child object is not of the same type.

After doing this:

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

I get that the first object has a child property of type Object with data. However, the second object has a child property of type Observable , which, when unpacked, returns null.

How can I do this in both cases, the objects are of the same type, even one has a value and the other is null. Changing the way the server behaves is not an option. I expect Object and null or both Observables .

JsFiddle is here .

+7
knockout-mapping-plugin
source share
2 answers

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

So, if you want to have 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 demo.

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); 
+4
source share

As already mentioned, the solution is a matching parameter, but be sure to always check the .data parameters for a null value and then return an empty ko.observable (), otherwise you will have a lot of binding problems! I spent a lot of time on this.

 var mappingOptions = { child: { create: function (options) { return options.data != null ? ko.observable(ko.mapping.fromJS(options.data)) : ko.observable(); } } } 
0
source share

All Articles