强制运行计算属性函数 [英] Force a computed property function to run
问题描述
给出计算属性
vm.checkedValueCount = ko.computed(function(){
var observables = getCurrentValues(); //an array of ko.observable[]
return _.filter(observables, function(v) { return v() }).length;
});
假设getCurrentValues()可以返回不同的可观察对象集,这些可观察对象集在代码的其他地方进行了修改(并且来自比observableArray更复杂的结构).
suppose getCurrentValues() can return different sets of observables which are modified elsewhere in the code (and comes from a more complex structure than an observableArray).
我需要checkedValueCount
随时进行更新
- 其依赖项之一更改
- getCurrentValues()返回一组不同的可观察值.
问题在于,ko.computed
似乎记住了最后一个返回的值,并且仅在依赖项更新时才更新.这可以处理第一种情况,但不能处理后者.
The problem is that ko.computed
seems to memoize the last returned value and only update when a dependency updates. This handles the first case but not the latter.
我正在寻找的是一种强制重新运行checkedValueCount的方法.我可以使用的东西是这样的:
What I'm looking for is a way to force checkedValueCount to re-run. Something which I can use like:
changeCurrentValues();
vm.checkeValueCount.recalculate();
考虑到我拥有的话,最简单地输入
Put most simply, given that I have
a = ko.computed(function() { return Math.random() })
如何强制两次调用a()
以返回不同的值.
how can I force invoking a()
twice to return different values.
推荐答案
我意识到我的第一个答案错过了您的观点,并且无法解决您的问题.
I realized my first answer missed your point, and won't solve your issue.
问题在于,只有在存在一些可观察到的强迫其重新评估的情况下,计算者才会重新评估.没有原生方法可以强制计算结果重新评估.
The problem is that a computed will only reevaluate if there is some observable that forces it to re-evaluate. There is no native way to force a computed to re-evaluate.
但是,您可以通过创建一个虚拟的可观察值,然后告知其订户它已更改,来解决一些黑客问题.
However, you can get around this with some hackery by creating a dummy observable value and then telling its subscribers that it has changed.
(function() {
var vm = function() {
var $this = this;
$this.dummy = ko.observable();
$this.curDate = ko.computed(function() {
$this.dummy();
return new Date();
});
$this.recalcCurDate = function() {
$this.dummy.notifySubscribers();
};
};
ko.applyBindings(new vm());
}());
这是一个小提琴,显示了这种方法
这篇关于强制运行计算属性函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!