1

I have a JSON structure containing arrays of arrays. I have a View Model that defines objects with Observable Arrays containing Observable data, and then nesting those objects in other Arrays and Observables.

What is the simplest way to load a View Model containing nested Observable Arrays containing Observable data?

Example: http://jsfiddle.net/uyQb6/1/

2 Answers 2

4

You could explore using the mapping plugin, but the options object would get complicated as each create callback would have to call the mapping plugin again and then add any dependentObservables and it would be easier to make all of the properties observables.

You can stick with your constructors though and use something like ko.utils.arrayMap, which is just a simple function that loops through an array and remaps each item to whatever you return from the function that you supply.

Here is your sample with the ko.utils.arrayMap calls added: http://jsfiddle.net/rniemeyer/VUfSS/

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

1 Comment

Yeah, I started down that path after finding this post on your blog at knockmeout.net, but I didn't know if there was a better way. Thanks!
0

Update: If your nested list is depend on main list this is your solution, otherwise @rp-niemeyer solution is the best.

If I got it right, lets say you have JSON data like this:

{
    appId: 1,
    appName: 'my app 1',
    modules:[
        {module1:1, moduleName: 'module 1'}, {module1:2, moduleName: 'module 2'}]
},
{
    appId: 2,
    appName: 'my app2',
    modules:[
        {module1:3, moduleName: 'module 3'}, {module1:4, moduleName: 'module 4'}]
}

This will be your viewModel:

function myViewModel(){
    var self = this;
    self.appList = ko.observableArray(data);
    self.moduleList = ko.observableArray([]);

    // Set selectedApp in order to fill modulesList
    self.selectedApp = ko.observable();
    self.selectedApp.subscribe(function(v){
        // updates module list whenever selected app gets value.
        moduleList(v.modules);
    });
}

I didn't test it but I'm sure you've got the idea.

Comments

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.