我有一个 ko.computed
函数,它确定 ko.observableArray()
中的当前项目是否有效。
但是,计算函数不会对数组中的每一项都执行
JavaScript:
var viewModel = {
items: ko.observableArray(["value 1", "value 2", "value 3"]),
};
viewModel.isValid = ko.computed(function() {
// doesn't gets executed for each item
console.log(this);
return true;
}, viewModel);
ko.applyBindings(viewModel);
HTML:
<script type="text/html" id="item-template">
<span data-bind="css: { 'valid': $root.isValid }, text: $data"></span>
</script>
<!-- ko template: { foreach: items, name: 'item-template' } --><!-- /ko -->
最佳答案
ko.computed
不会自动遍历所有项目。你需要自己做:
viewModel.isValid = ko.computed(function() {
ko.utils.arrayForEach(this.items(), function(item) {
console.log(item);
});
return true;
}, viewModel);
演示 JSFiddle .
ko.computed
只为您提供在其依赖的可观察变量之一发生变化时重新计算其值的功能。
关于javascript - 为数组中的每个项目计算的 jQuery Knockout 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21109300/