我的代码中有一个这样的 knockout 计算函数
self.TestFunction = ko.computed(function () {
//Some logic
}, self).extend({ rateLimit: 100 });
该函数会自动执行,无需绑定(bind)到任何 html 元素。我想知道背后的原因。
最佳答案
I would like to know the reason behind it
通常,您使用 ko.compulated
作为其返回值。 但是,这并不是它们的唯一用途。通常,您会看到使用 ko.compulated
的代码更像是一种订阅
多个值的奇特方式。例如
// 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 能够“运行”记录到控制台的副作用,它必须找出它的依赖项是什么。它通过运行 someSideEffect
函数一次来实现这一点。
正如评论中提到的,pureCompulated
属性的工作方式有所不同。它们仅在请求其自己的值后才运行其内部函数。
简而言之:
ko.compulated
在创建时运行其内部函数,因为它支持副作用。ko.pureCompulated
仅在请求其值时运行一次,并在没有依赖项时暂停。
关于javascript - 为什么计算函数会自动运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476124/