问题描述
我的代码中有一个这样的敲除计算函数
I have one knockout computed function like this in my code
self.TestFunction = ko.computed(function () {
//Some logic
}, self).extend({ rateLimit: 100 });
此函数自动执行,而没有绑定到任何html元素.我想知道其背后的原因.
This function is executed automatically without its been binded to any html element. I would like to know the reason behind it.
推荐答案
通常,您将ko.computed
用作其返回值. 但是,这不是他们的唯一用途.通常,您会看到使用ko.computed
的代码,更像是将subscribe
转换为多个值的一种奇妙方式.例如
Usually, you use a ko.computed
for its return value. However, this isn't their only use. Often, you'll see code using a ko.computed
more like a fancy way to subscribe
to multiple values. For example
// Please note, I do *not* recommend these kinds of structures, I'm merely
// showing knockout allows them
const input1 = ko.observable("");
const input2 = ko.observable("");
const input3 = ko.observable("");
ko.computed(function someSideEffect() {
input1();
input2();
input3();
console.log("Some value has changed!");
});
现在,要使敲除能够运行"登录到控制台的副作用,它必须找出其依赖项.通过运行someSideEffect
函数一次.
Now, for knockout to be able to "run" the side effect of logging to console, it has to find out what its dependencies are. It does so by running the someSideEffect
function once.
如注释中所述,pureComputed
属性的工作方式不同.他们仅在请求 own 值后才运行内部函数.
As mentioned in the comments, pureComputed
properties work differently. They only run their inner function once their own value is requested.
简而言之:
-
ko.computed
在创建时运行其内部功能,因为它支持副作用. -
ko.pureComputed
仅在请求其值时运行一次,并在没有依赖项时暂停.
ko.computed
runs its inner function upon creation because it supports side-effects.ko.pureComputed
only runs once when its value is requested, and pauses when there are no dependencies.
这篇关于为什么计算函数自动运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!