在knockout.js中创建observable的动态数组

Create dynamic array of observableArray in knockout.js

本文关键字:动态 数组 observable 创建 knockout js      更新时间:2023-09-26

在我的视图模型中有以下函数来构建一个可观察数组的动态数组,按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))')
            });
        });
    }

我会重新调整你的对象:

 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));
        });
    });
}