问题
I have used the search engine, and found alot of answers, but I am stuck on a problem. The problem is that the child collection mapping seems to not fire. In the below code the alert "Groups created", but the "Root created"-alert is shown.
var mapping = {
'Groups': {
create: function (options) {
var lang = ko.observable(ko.mapping.fromJS(options.data));
alert('Groups created');
return lang;
}
},
create: function (options) {
var innerModel = ko.mapping.fromJS(options.data);
alert('Root created');
innerModel.ajaxSave = submitFormWithAjax;
return innerModel;
}
}
var viewModel = null;
function loadViewModel(model, offlineCache, key) {
viewModel = ko.mapping.fromJS(model, mapping);
if (typeof extendViewModel == 'function') {
extendViewModel();
}
ko.applyBindings(viewModel);
}
and my json data looks like this
{
"Groups": [
{
"Texts": [
{
"Language": {
"Id": 1,
"Name": "English",
"Lcid": 2057
},
"Id": 1,
"Value": "Display name"
},
{
"Language": {
"Id": 2,
"Name": "Swedish",
"Lcid": 1053
},
"Id": 2,
"Value": "Visningsnamn"
}
],
"Id": 1,
"InternalName": "3dc075e3-ff96-4044-b9bb-4a0404912866",
"DisplayName": "Display name"
}
],
"AvailableLanguages": [
{
"Id": 1,
"Name": "English",
"Lcid": 2057
},
{
"Id": 2,
"Name": "Swedish",
"Lcid": 1053
}
]
}
Why is my Groups-created alert fired?
回答1:
You cant have create functions on more than one level for some reason with the mapping plugin, you can do this
RootViewModel = function(data) {
this.stuffAddedToViewModelBeforeMapping = "Hej på dig";
var mapping = {
Groups: {
create: function(options) {
return new GroupViewModel(options.data);
}
},
AvailableLanguages: {
create: function(options) {
return new LanguageViewModel(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, this);
};
LanguageViewModel = function(data) {
ko.mapping.fromJS(data, {}, this);
}
GroupViewModel = function(data) {
ko.mapping.fromJS(data, {}, this);
};
http://jsfiddle.net/42ZwC/
Lycka till!
来源:https://stackoverflow.com/questions/24199726/child-collection-mapping-not-firing