Jquery Knockout:ko.computed()vs经典函数?

时间:2013-04-29 08:17:13

标签: javascript jquery knockout.js

我有一个视图模型

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可观察时,两段都会更改文字。

那么,使用ko.computed和classinc函数有什么区别?

2 个答案:

答案 0 :(得分:7)

经典函数在其依赖的observable改变时不会被执行,但只有当它被独占调用时,另一方面,只要它可能使用的任何可观察属性发生变化,计算函数就会被执行。

您查看绑定上的当前has()和执行调用。这使得该物业成为现成的。当你指定计算机时,要发生两种方式绑定,你应该写:

text: applicationsText_computed

What if you’ve got an observable for firstName, and another for lastName, and you want to display the full name? That’s where computed observables come in - these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.

答案 1 :(得分:2)

是的,当applications发生变化时,两个段落都会发生变化。这是由于隐式计算的observable,它是由knockout创建的。它类似于在你的html标记中写:
<p data-bind="text: 'You have ' + applications() + ' applications'"></p>
在所有三种情况下,knockout创建计算的observable并跟踪它依赖于可观察的applications。因此,“计算”和“经典函数”都会导致隐式计算可观察。正如XGreen所指出的,使用计算机的正确方法是text: applicationsText_computed

所以在这个简单的例子中你可以使用“经典功能”。对我来说,如果它是唯一的地方,在html标记中编写它会更简单。但有两点重要。第一个,正如我所说,无论如何计算的observable是明确地或隐含地创建的。第二个是计算的observable具有更多的功能。例如。您可以在代码中明确订阅它:applicationsText_computed.subscribe(function(newValue) {...}) 此外,您可以使用显式读写访问器创建observable。检查the documentation以获取其他信息。因此,计算的observable与函数完全不同。