javascript - 更新 KnockoutJS 关联 observableArray 值

标签 javascript knockout.js associative-array

这应该很简单。

我有一个带有名称和 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/

相关文章:

javascript - jQuery - 意外的标识符

php - KnockoutJS - 发送包含 javascript 对象值的表单会导致超时

javascript - KnockoutJS - 单击按钮后数据绑定(bind)不会更改文本

javascript - 事件发生后 knockout JS textInput

php - Array Unique with Associative Array - 删除重复项

PHP - 自动创建多维数组

javascript - AngularJS Controller 未显示结果

javascript - Grunt.js : htmlhint - targeting all html files

javascript - 为什么不在括号中运行我的js代码?

php - 如何在以下场景中操作数组?