knockout.mapping
knockout.mapping copied to clipboard
Options for toJS generation (similar to fromJS)
Would it be possible to have the same control over object generation when performing toJS(viewModel)
as we have when calling fromJS
through the mapping
parameter?
In other words, just like we have a "create" mapping when converting to the VM:
var mapping = {
'children': {
create: function(options) {
return new myChildModel(options.data);
}
}
}
ko.mapping.fromJS(data, mapping)
could we have a similar mapping:
var mapping = {
'children': {
create: function(options) {
// i realize this is not a good example, but it's illustrative.
return { id: options.data.id, name : options.data.firstName };
}
}
}
ko.mapping.toJS(data, mapping)
I am also interested in this feature. Is there already news if and when it will be implemented?
I was digging around in knockout.mapping looking for just this feature. Here is my recommendation: In addition to the core methods of create
, key
, and update
, add a new one for the "uncreate" method, where create
is used for fromJS()/fromJSON()
and uncreate
is used for toJS()/toJSON()
. Looking at a thesaurus, possible choices could be 'restore', 'respond', I dunno. An example:
var mapping = {
'child': {
create: function (options) {
return new ChildVM(options.data);
},
restore: function (data) {
// Where data is the ChildVM
return { id: data.id(), name : data.firstName() }
// Or, for my case
return data.toJSON();
}
}
}
I would really like this as some of the sub-viewmodels are also using mapping with various include
, copy
, etc., but the sub-mapping ignored when the parent.toJSON()
is called and instead the original parent's mapping is used. I can work on getting a pull request put together, but I've never done it before so no promises. Thanks!
This feature is a real requirement for us. If you create an object with fromJS using the "create" mapping, then convert the object back using toJS, you get a different result!
The fix (as described above) would be to have a "restore" option (which could be specified in the toJS method, to be used in fromJS), which knows how to reverse the operation.
What does everyone else think?
This would be awesome for us too, because it seems like toJS will not ouput computed observables. Is there a way I could achieve this?
+1