观察\更新ObservableArray中的数据

时间:2012-11-20 17:37:34

标签: knockout.js

我正在学习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视图中更改复选框时更新选中的值,但这不会发生。在状态变化的背后,我想采取一些行动。在这种情况下,操作将是在图表中显示数据系列(仍然要执行该部分)。

提前致谢, 马特

1 个答案:

答案 0 :(得分: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”)

相关问题