I'm running into an issue with KnockoutJS's mapping plugin where I need to do the following:
In this fiddle example I am trying have the children properly mapped to their custom creation. The expected result is that each of the children have the added description property. From the fiddle, the result should read:
I can demonstrate the expected behaviour in this this fiddle example. Notice that in this code I must have two data sets, with the first having an empty array of children objects. The following line of code will cause the customized creation of child objects:
ko.mapping.fromJS(additionalData, parentMapping, viewModel);
Unfortunately, this requires both having empty initial children and mapping twice. This is not acceptable as the code in reality has a much deeper hierarchy.
In addition to the above, I've tried adding the following code in the parentMapping:
var mapping = { 'ignore': ["children"] };
var innerModel = ko.mapping.fromJS(options.data, mapping);
//for brevity
innerModel.children = ko.mapping.fromJS(options.data.children, childMapping);
This has the effect of mapping the children objects on the initial mapping. However, all subsequent mappings the children property is ignored.
Is there a way to customize the creation of both a parent and child object with Knockout Mapping?
Thank you.
http://jsfiddle.net/5cfa3/23/
var viewModel = {};
var data = {
id: "1",
firstName: 'Adam',
lastName: "Smith",
children: [ {id: "2", name: "Bob", age: 5}, {id: "3", name: "Chris", age: 7 }]
};
var Parent = function(data){
ko.mapping.fromJS(data, mapping, this)
};
var mapping = {
create:function(options){
var parent = new Parent(options.data);
parent.fullName = ko.computed(function(){
return parent.firstName() + " " + parent.lastName();
});
return parent;
},
'children': {
create: function(options) {
options.data.description = ko.computed(function(){
return options.data.name + " is " + options.data.age + " years old ";
});
return ko.mapping.fromJS(options.data);
}
}
};
viewModel = ko.mapping.fromJS(data, mapping);
ko.applyBindings(viewModel);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With