Reputation: 119
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))')
});
});
}
Upvotes: 0
Views: 2823
Reputation: 5147
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));
});
});
}
Upvotes: 2