I use the mapping plugin with my own prototype types
From JSON
var mapping = {
Children: {
create: function(options) {
return ko.mapping.fromJS(options.data, {}, new ChildViewModel());
}
}
};
$.getJSON(url, null, function (data) {
var model = ko.mapping.fromJS(data, mapping, new RootViewModel());
ko.applyBindings(model);
});
To JSON
var data = ko.mapping.toJSON(this);
The json data has the orignal child items and the newly added items are just empty json objects {}
I add child items like this from the root model
addChild: function () {
this.Children.push(new ChildViewModel());
}
Whats wrong?
Update:
A fiddle that recreates my problem
Update2
Tested another approach after some google findings still no dice :/
Update after answer
I have data both on main model and child models that need to be mapped and then serilized to JSON
So i need it to map both main model and children, maybe this is not possible?
Update CRUD operations how?
I’ve gotten further thanks to google and Madcapnmckay here at Stackoverflow. I have one final problen, and after this I think I can do everything with the mapping plugin that we currently are doing with our manual mappers (We are soon hitting over 100 view models so manual mappers are starting to frustrate us).
I havent found a way for the mapper to handle CRUD scenarios, lets say you have 5 items when you load the view, these have id’s, then you add 2 items, these get id: 0. Then we save send the entire VM to backend these new rows get new Id’s. I call the mapper plugin on the update but it fails with When calling ko.update*, the key '0' was not unique!
You can offcourse do
this.items.remove(function(item) { return item.id() == 0;});
Just before calling the mapper, But can the mapper do it for you? Thanks!
The issue is that your dynamically added children are not created by the mapping plugin. You can solve this and clean up your code by moving the mapping inside your objects like so.
http://jsfiddle.net/madcapnmckay/3bWcF/1/
Hope this helps.