我在视图模型中有以下函数来构建一个可观察数组的动态数组,由item.array_name字段命名。但是我遇到了使用Document对象填充数组的问题。这样我就可以在每个数组的页面中多次重复使用相同的HTML界面。有人能指出我出错的方向,还是他们更好的做法?
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 :(得分:2)
我会重新调整你的对象:
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));
});
});
}