这应该很简单。
我有一个带有名称和 bool 值的关联可观察数组。
this.items = ko.observableArray([
{ name: "name1", boolVal: true },
{ name: "name2", boolVal: true },
]);
然后是一个简单的函数来改变 boolVal。
this.changeValue = function (item) {
item.boolVal = false;
};
当我调用 changeValue 函数时,boolVal 确实发生了变化(请参阅我的 jsfiddle 中的 console.log(data)),但 View 没有更新。屏幕上的值保持“真”。我必须对 KnockoutJS 的工作方式做出错误的假设。
JS Fiddle Link
最佳答案
为了 KO 更新 UI,您需要具有可观察的属性:
this.items = ko.observableArray([
{ name: "name1", boolVal: ko.observable(true) },
{ name: "name2", boolVal: ko.observable(true) },
]);
并将其设置为:
this.changeValue = function (item) {
item.boolVal(false);
};
ko.observableArray
仅跟踪项目添加和删除。因此,如果其中一项发生更改,它不会通知 UI。为此,您需要拥有 ko.observable
元素上。演示 JSFiddle.
关于javascript - 更新 KnockoutJS 关联 observableArray 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15795564/