Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mapping partial model into existing viewModel #213

Open
pmatalon opened this issue May 25, 2016 · 0 comments
Open

mapping partial model into existing viewModel #213

pmatalon opened this issue May 25, 2016 · 0 comments

Comments

@pmatalon
Copy link

Hi,
I'm having trouble mapping json data to my viewModel when the data doesn't contain all the properties defined in the viewModel.
Basically I want to reload saved data from my database into my form. My form has a viewModel containing all kinds of observable properties (included nested properties). The json data I receive from the server is mapped this way:

ko.mapping.fromJS(data, mappingOptions, self.model);

Then, when I want to send to the new values to the server to be saved again in database, I do this:

var data = mapping.toJSON(self.model, mappingOptions);

When the user saves the form for the first time, all the controls he left empty won't appear in the saved model (which is fine with me). Therefore, when the data is later reloaded from the DB into the form, it does not contain all the properties.
I would expect that the viewModel I map (self.model) be updated with the values that are present in the data object, and the other properties be left as is, but instead the binding is broken for those properties : even if the user now fills the appropriate controls in the form, all the properties that were absent in the loaded data won't be there after the call to mapping.toJSON.
As far as I understand the documentation, that's the way it's supposed to work:

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

Alright, but would there be a way to somehow merge incomplete data into an already created viewModel without breaking the binding of the missing properties?
For now, I just add all the fields I have defined in my viewModel in the 'include' parameter of the mapping options, which solves the issue, but I just feel that I'm missing the point of using knockout if I have to list all the fields of the form in an array.
What do you think? Do you have a better solution?
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant