this post is a follow-up to this one.
I've updated the code as followed:
viewModel.getQuotesSuccess = function (result) {
var myCoverQuotesViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.Childs = ko.observableArray(ko.utils.arrayMap(data.Childs, function (c) {
return new myCoverQuotesViewModel(c);
}));
self.selectedChild = ko.observable();
self.showChildren = ko.computed(function () {
return self.selectedChild()
&& self.selectedChild().Childs().length > 0;
});
var mapping = {
'CoverQuotes': {
create: function (options) {
return new myCoverQuotesViewModel(options.data);
}
}
}
ko.mapping.fromJS(result, mapping, viewModel);
};
The viewModel would look something like this:
var viewModel = {
CoverQuotes: [{id: 1, label:'test', Childs:[{id: 2, label:'child1'}]]
};
So in a nutshell, I have an array of CoverQuotes, which each element also contains an array of CoverQuotes (and so on).
The problem I have with this mapping, is with the Childs observable array. When calling:
return new myCoverQuotesViewModel(options.data);
for the main object, it works fine. However when calling the constructor from within th arrayMap function, then that line:
ko.mapping.fromJS(data, {}, self);
doesn't do anything.
As a result, nested children are assigned the properties selectedChild and showChildren but they are missing all others (like id and label in this example).
What am I missing so the mapping also works for children ?