简体   繁体   中英

Knockout - Updating observableArray in View Model

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 :)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM