为什么计算函数会自动运行
why computed function runs automatically
我的代码中有一个像这样的淘汰计算函数
self.TestFunction = ko.computed(function () {
//Some logic
}, self).extend({ rateLimit: 100 });
此函数自动执行,无需绑定到任何 html 元素。我想知道背后的原因。
I would like to know the reason behind it
通常,您使用 ko.computed
作为其 return 值。 但是,这不是它们的唯一用途。通常,您会看到使用 ko.computed
的代码更像是一种将 subscribe
用于多个值的奇特方式。例如
// 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!");
});
现在,为了让 knockout 能够 "run" 记录到控制台的副作用,它必须找出它的依赖项是什么。它通过 运行ning someSideEffect
函数 once.
来实现
如评论中所述,pureComputed
属性的工作方式不同。一旦他们的自己的值被请求,他们只会运行他们的内部函数。
简而言之:
ko.computed
运行因为它支持 side-effects. 创建时的内部功能
ko.pureComputed
仅在请求其值时 运行s 一次,并在没有依赖项时暂停。
我的代码中有一个像这样的淘汰计算函数
self.TestFunction = ko.computed(function () {
//Some logic
}, self).extend({ rateLimit: 100 });
此函数自动执行,无需绑定到任何 html 元素。我想知道背后的原因。
I would like to know the reason behind it
通常,您使用 ko.computed
作为其 return 值。 但是,这不是它们的唯一用途。通常,您会看到使用 ko.computed
的代码更像是一种将 subscribe
用于多个值的奇特方式。例如
// 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!");
});
现在,为了让 knockout 能够 "run" 记录到控制台的副作用,它必须找出它的依赖项是什么。它通过 运行ning someSideEffect
函数 once.
如评论中所述,pureComputed
属性的工作方式不同。一旦他们的自己的值被请求,他们只会运行他们的内部函数。
简而言之:
ko.computed
运行因为它支持 side-effects. 创建时的内部功能
ko.pureComputed
仅在请求其值时 运行s 一次,并在没有依赖项时暂停。