js and the knockout mapping plugin
my problem is this:
i have model and i am adding observables to it during runtime like so:
viewModel[value] = new ko.observable(valueFromTextBox);
this works ok and the observables are binded to the screen and this part works fine
the problematic part is when i try to take that model and convert it to JSON like so:
var JSON = ko.mapping.toJS(page.model);
when i debug this i see that page.model has all the new observables. but my final JSON has only the ones who were in the model to begin with. not the ones added later in runtime.
what is the correct way to add observables during runtime?
thanks
EDIT:
I will describe my entire scenario and then post my solution as an answer.
I am using ASP.Net MVC, i created a view model then made an ajax call to receive my actual model form the server. then use:
ko.mapping.fromJS(model, page.model);
after that the binding occurs later when the user adds new fields i used:
viewModel[value] = new ko.observable(valueFromTextBox);
and in the end before sending it back to the server i used:
var JSON = ko.mapping.toJS(page.model);
in which point the added fields were not present in the JSON.
after debugging
i realized the function reads the values in the dictionary
which is creted during the use of the toJS function
anyway because my new added observables were not present in the
__ko_mapping__.mappedPropertiesdictionary theywere also not present in the JSON object returned to me using the ko.mapping.toJS function
so what i did to make it work is this:
I add an observable to my model but update my mappedProperties dictionary as well
and that’s it. now when calling
ko.mapping.toJSmy entire model is returned as a JSON object including my added observables.I realize this is probably not the most elegant way of doing it. but it sure does work great.