jQuery淘汰赛:ko.computed()vs经典函数? [英] Jquery Knockout: ko.computed() vs classic function?

查看:87
本文介绍了jQuery淘汰赛:ko.computed()vs经典函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图模型

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

如果您对firstName有一个可观察值,对于lastName有一个可观察值,并且想要显示全名?那就是计算可观察值的来源-这些函数依赖于一个或多个其他可观察值,并且只要这些依赖关系中的任何一个发生更改,它们就会自动更新.

这篇关于jQuery淘汰赛:ko.computed()vs经典函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆