1

I wish to save my view model to a database as a JSON string. The idea is that I can then re-load my view model by reading the JSON back and using the direct approach to load my view model's data:

From the Knockout documentation:

// Load and parse the JSON
var someJSON = /* Omitted: fetch it from the server however you want */;
var parsed = JSON.parse(someJSON);

// Update view model properties
viewModel.firstName(parsed.firstName);
viewModel.pets(parsed.pets);

That all works great but where I've already initialised my model and I'm simply updating it with one that I've already saved, I can't see how I can select the originally selected entry in the array's drop-down list.

To put it another way, the pets drop-down list is selected as "Cat" when I save my model. I then change the drop-down list selection to "Dog". On re-loading the saved model, I need my drop-down list selection to be reset to "Cat".

I'm a bit concerned about this because I have some arrays of objects which also need to be read in from the saved model and it's looking like it's going to be very difficult to do.

Any ideas or suggestions are welcome :)

1 Answer 1

1

What you are looking for is the mapping plugin for Knockout. http://knockoutjs.com/documentation/plugins-mapping.html

It has methods that handle both JSON to observables and back.

So in your example you could do:

var viewModel = ko.mapping.fromJSON(someJSON);

And when you're ready to go back to the server:

var jsonData = ko.mapping.toJSON(viewModel);

There are also object literal helpers if you need that (ko.mapping.toJS & ko.mapping.fromJS)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the suggestion - I'm using a framework so I don't know if I can install a plugin but it's surely just a matter of referencing the additional file?
Sorry, I meant to say as well that I've figured out what was happening when my code failed to initialise the observable arrays - my web services wasn't returning the data in time but setting async=false fixed that. The next issue is that, as mentioned, I have arrays of objects which then include nested arrays. I've yet to find how to initialise such complex objects. I'll create a new question for that one though :) Thanks again.
<updated> I tried the plugin and it seems to work for the basic observables but doesn't do anything with the arrays of complex objects - looks like I'll have to do these manually.
We are using it for some pretty complex objects and it maps everything for us. Not sure what you're seeing, but it should handle your situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.