0

I have the following function in my view model to build up a dynamic array of observable arrays, named by item.array_name field. However I am getting stuck populating the arrays with the Document objects. This is so I reuse the same HTML interface multiple times within the page per array. Can someone point me in the direction I am going wrong, or is their a better approach?

     self.getDocument = function(){
        //Reset arrays
        self.documents.removeAll();

        //Dynamically build arrays
        $.getJSON("/Documentation/Get-Section", function(allData) {
            $.map(allData, function(item) { 
                var obj = {};
                obj[item.array_name] = ko.observableArray([]);
                self.documents(obj)                   
            })

        });

        //Add document object to the arrays
        $.getJSON("/Documentation/Get-Document", function(allData)
            $.map(allData, function(item) { 
                var temp_array = 'self.documents.'+item.array_name
                eval(temp_array+'(new Document(item))')
            });
        });

    }
0

1 Answer 1

2

I'd rejig your objects:

 self.getDocument = function(){
    //Reset arrays
    self.documents.removeAll();

    //Dynamically build arrays
    $.getJSON("/Documentation/Get-Section", function(allData) {
        $.map(allData, function(item) { 
            var section = { name: item.array_name, documents: ko.observableArray([])};
            self.documents.push(section);
        })

    });

    //Add document object to the arrays
    $.getJSON("/Documentation/Get-Document", function(allData){
        $.map(allData, function(item) { 
        var section = ko.utils.arrayFirst(self.documents(), function(documentSection) {
            return documentSection.name === item.array_name;
        });
            section.documents.push(new Document(item));
        });
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This works great, it's a much better technique to set the array name as a value within the object. Muchas gracias!
Just as an added query: Could you shed any light on how I could loop through these sections within knockout to reuse the section of HTML that makes up the interface?
Use a foreach: documents section in your html, and that will be used for each one. It might be an idea to rename the documents object to documentSections or something, given that it's not strictly speaking documents.

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.