我有一个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);
目录:
<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
仅为您提供在其依赖的可观察对象之一发生更改时重新计算其值的功能。