计算观察的问题

Issue with computed observable

本文关键字:问题 观察 计算      更新时间:2023-09-26

我使用的是knockout-2.2.0.js。我有以下模型:

function Person(name, age, city)
{
 this.Name = ko.observable(name);
 this.Age = ko.observable(age);
 this.City = ko.observable(city);
 ko.computed(function(){
   //Is there any way to execute this section whenever Name, Age, City any 
   //of this observable changes without including this.Name, this.Age and 
   //this.City inside it
 }, this).extend({ throttle: 500 });
}

我知道我问的有点奇怪,但我想知道有没有办法做到这一点?

使用自定义绑定。自定义绑定内部有一个'update'函数。当任何可观察值被改变时,这个更新函数会自动调用

http://knockoutjs.com/documentation/custom-bindings.html

最简单的方法是在您的计算中调用ko.toJS(this)。这通常用于从视图模型中构建一个"干净"的对象。作为构建该对象的一部分,它将展开所有可观察对象(这会创建依赖关系)。因此,当任何依赖项发生变化时,您的计算将被触发。

这是类似"脏标志"的基础:http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

您可以通过这种方式将throttle与您的计算机一起使用。