Problem
I'm trying to send a modified viewModel back to my server. Unfortunately I have to create my viewModel using ko.mapping.fromJSON() and some mappingOptions, which is working fine. Now I need an easy way to convert the created viewModel back to the original scheme.
Desired result
I want to convert this:
var myModel = {
simpleProp: "test",
complexProp: {
simpleProp2: "test2",
simpleProp3: "test3"
}
};
into that (JS):
var myModel = {
simpleProp: "test",
modifiedToSimpleProWithNewName: "test2"
};
giving me this JSON:
{"simpleProp":"test","modifiedToSimplePropWithNewName": "test2"}
Attempts
I was thinking that, since ko.mapping.toJSON has a mapping parameter, it is as easy as creating another mapping for this method. But it seems like ko.mapping is actually ignoring my custom property creation:
var mappingOptions = {
// ignored
'simpleProp': {
create: function (thing) {
return "Changed simpleProps value";
}
},
// working
ignore: ["simpleProp3"]
};
Further Information
I've created a jsFiddle for you.
Please notice: I've simplified the example removing the model generation using fromJSON:
// created and modified by ko.mapping.fromJSON - with custom mapping!
var myModel = {
simpleProp: "test",
complexProp: {
simpleProp2: "test2",
simpleProp3: "test3"
}
};
The result will be:
{"simpleProp":"test","complexProp":{"simpleProp2":"test2"}}
And as you can see, the ignore option will be applied, while the 'simpleProb'/create won't.
Any help is much appreciated. Thank you!
PS: I know that this mapping will not achive the desired result. It was just a "will 'simpleProp' be modified?"-test.
Aucun commentaire:
Enregistrer un commentaire