knockout.mapping icon indicating copy to clipboard operation
knockout.mapping copied to clipboard

Options for toJS generation (similar to fromJS)

Open philipmat opened this issue 13 years ago • 5 comments

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)

philipmat avatar Feb 24 '12 16:02 philipmat

I am also interested in this feature. Is there already news if and when it will be implemented?

SebaVDP avatar May 25 '12 10:05 SebaVDP

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!

timhall avatar Jun 08 '12 01:06 timhall

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?

richardhills avatar Mar 06 '13 12:03 richardhills

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?

marcofiset avatar Feb 10 '14 17:02 marcofiset

+1

remye06 avatar Aug 26 '14 23:08 remye06