I have the following model:
var model = {
A: 'One',
B: 'Two',
C: 'Three'
};
I bind various UI elements to these fields, which works great. However, I convert the model back to a JavaScript object so I can save any changes to the server:
var goingToServer = ko.toJS(model);
goingToServer
will include properties A, B and C. However, let's say property C is a huge chunk of data that will never change. I'd like to avoid sending this back to the server.
Is there a way to make toJS()
only include a predefined set of fields when converting a model back to a JavaScript object?
One thing I've been investigating is the Knockout Mapping plugin. It has a setting called include which is documented as such:
When converting your view model back to a JS object, by default the mapping plugin will only include properties that were part of your original view model, except it will also include the Knockout-generated _destroy property even if it was not part of your original object. However, you can choose to customize this array:
However, it appears this plugin doesn't work as documented, as ko.mapping.toJS()
will still include A, B and C, even if I pass in an include
array of ['A', 'B']
. I'm guessing this feature is intended to include additional fields that were not in the original model.
Is there a way to exclude certain properties when converting a model back to a JavaScript object, short of doing something hacky such as generating the object and manually removing the properties I don't want before sending to the server?
Have you tried the ignore
keyword? It has a similar usage to the include:
var mapping = {
'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
var viewModel = ko.mapping.toJS(data, mapping);
You could just use ignore when you do the original mapping of the server data, then it won't be on your object at all when you convert it back to JS.