jQuery淘汰赛:ko.computed()vs经典函数? [英] Jquery Knockout: ko.computed() vs classic function?
问题描述
我有一个视图模型
function ViewModel() {
this.applications = ko.observable(10);
this.applicationsText_computed = ko.computed(function () {
return "You have " + this.applications() + " applications";
});
this.applicationsText_classinc = function () {
return "You have " + this.applications() + " applications";
};
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<p data-bind="text: applicationsText_computed()"></p>
<p data-bind="text: applicationsText_classic()"></p>
当我更改为applications
可观察时,两个段落都更改了文本.
Both paragraphs changes the text when i change applications
observable.
然后,使用ko.computed
和classinc函数有什么区别?
Then, what is the difference between using a ko.computed
and a classinc function?
推荐答案
经典函数只有在其依赖的可观察变量发生变化时才会执行,而只有在其被唯一调用时,计算函数才能尽快执行.可观察的属性,它可能正在使用更改.
The classic function will not be executed when its dependent observables change but only when it is exclusively called, the computed function on the other hand gets executed as soon as any observable property it might be using changes.
您查看当前绑定上有(),并且该调用被执行.这会将物业变成仅准备就绪的物业.当您指定computes时,要使两种方式的绑定都发生,您应该编写:
You view currently has () on your binding and that a execution call. which turns the property into a ready only. When you specify computeds, for both way bindings to happens you should write:
text: applicationsText_computed
这篇关于jQuery淘汰赛:ko.computed()vs经典函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!