Guy Schaller
Guy Schaller

Reputation: 4700

adding observables to model during runtime. but ko.mapping.toJS doesn't return them

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.

Upvotes: 2

Views: 1680

Answers (2)

Guy Schaller
Guy Schaller

Reputation: 4700

after debugging

ko.mapping.fromJS(model, page.model);

i realized the function reads the values in the dictionary

    __ko_mapping__.mappedProperties

which is creted during the use of the toJS function

var JSON = ko.mapping.toJS(page.model);

anyway because my new added observables were not present in the __ko_mapping__.mappedProperties dictionary they were 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:

viewModel[value] = ko.observable(valueFromTextBox);
viewModel.__ko_mapping__.mappedProperties[value] = true;

I add an observable to my model but update my mappedProperties dictionary as well and that's it. now when calling ko.mapping.toJS my 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.

Upvotes: 3

Tom W Hall
Tom W Hall

Reputation: 5283

Did you mean .toJSON rather than .toJS?

This situation worked for me, although I don't think you should use "new", it should just be:

viewModel['PropertyName'] = ko.observable(value);

Actually both ways worked for me, with and without new, but in all the documentation it's used without, like a factory method. Could you create a fiddle which demonstrates your problem?

Upvotes: 1

Related Questions