2

我正在学习 Knockout.js 并且我有一个关于更新嵌套数据的问题,我正在做的事情是可能的还是我需要重新考虑我的模型?

这是视图模型中的数据:

this.menu = ko.observableArray([
    {text: "one",
        children: [{text: "child 1.1", checked: true},{text: "child 1.2", checked: false}]},
    {text: "two",
        children: [{text: "child 2.1", checked: false},{text: "child 2.2", checked: true}]},
    {text: "three",
        children: [{text: "child 3.1", checked: false}]}
]);

这是小提琴:

http://jsfiddle.net/4aqrg/1/

数据在最后被写出,所以我们可以看到它的状态。

我希望在 HTML 视图中更改复选框时更新选中的值,但这并没有发生。在状态变化的后面我想采取一些行动。在这种情况下,操作将是在图表中显示一个数据系列(仍然要做那部分)。

在此先感谢,马特

4

1 回答 1

3

您的示例中的问题是您使数组可观察,但各个属性不可观察。

您需要使每个“已检查”属性 ko.observable 才能更新。

像这样:

this.menu = ko.observableArray([
        {text: "one",
            children: [{text: "child 1.1", checked: ko.observable(true)},{text: "child 1.2", checked: ko.observable(false)}]},
        {text: "two",
            children: [{text: "child 2.1", checked: ko.observable(false)},{text: "child 2.2", checked: ko.observable(true)}]},
        {text: "three",
            children: [{text: "child 3.1", checked: ko.observable(false)}]}
    ]);

如果您希望文本也可观察,则还必须将其包装起来: ko.observable("child 1.1")

于 2012-11-20T17:55:25.830 回答