3

我有一个对象(analysisLogData),用于使用 KnockoutJS 生成表。这是包含此对象的 viewModel:

function AppViewModel() {
    var self = this;
    self.analysisLogData = ko.observableArray();
    self.analysisLogTitle = ko.observable("Warnings")

    self.changeAnalysisLog = function(title) {
         self.analysisLogTitle(title)   
    }

    var data =

    {
        "Warnings": [
            {
                "number": 3002,
                    "description": "There may be a problem with the device you are using if you use the default profile"
            },

            {
                "number": 3001,
                    "description": "There may be a problem with the device you are using if you don't use the default profile"
            }

            ]

        ,
            "Errors": [
            {


                "number": 1000,
                    "description": "No networks are loaded"
            },

            {
                "number": 1002,
                    "description": "No devices are loaded"
            }]




    }


    self.addLog = function (type, content) {
        self.analysisLogData()[type].push(content);
    }

    self.analysisLogData.push(data)


}

ko.applyBindings(new AppViewModel());

您可以在 JSFiddle 中看到结果:http: //jsfiddle.net/etiennenoel/V4r2e/5/

我希望能够添加错误或警告而不会丢失已经存在的警告或错误。

我尝试在self.addLog函数中执行以下操作:

self.addLog = function (type, content) {
        self.analysisLogData()[type].push(content);
    } 

但它说它不能推送到一个未定义的对象......

4

2 回答 2

2

好的,在玩弄小提琴之后。我相信您需要对在可观察数组中推送数据的方式进行一些更改。但无需进行大量修改,请在此链接中检查我的解决方案。

jsfiddle 示例

self.addLog = function (type, content) {

    self.analysisLogData()[0][type].push({
        "number": 1002,
        "description": content
    });
}

并且数据对象应该是

"Warnings": ko.observableArray([........]),
"Errors": ko.observableArray([..........])

我做了两件事

  1. 将警告和错误修改为可观察数组
  2. 我推送了这个self.analysisLogData()[0][type].push中的数据,而不是self.analysisLogData()[type].push
于 2013-07-02T17:12:25.240 回答
0

self.analysisLogData()是一个包含错误/警告数组的数组。

我不确定这是否是您希望数据结构的方式。

要使小提琴正常工作,您可以将 addLog 函数替换为:

self.addLog = function (type, content) {
        self.analysisLogData()[0][type].push(content);
    }
于 2013-07-02T16:52:28.880 回答