【问题标题】:Jquery Knockout: ko.computed() vs classic function?Jquery Knockout:ko.computed() 与经典函数?
【发布时间】:2013-04-29 17:53:49
【问题描述】:

我有一个视图模型

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 observable 时,两个段落都会更改文本。

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

【问题讨论】:

    标签: javascript jquery knockout.js


    【解决方案1】:

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

    您的视图当前在您的绑定上有 () 并且是一个执行调用。这会将属性变成只准备好的。当您指定计算值时,对于发生的双向绑定,您应该编写:

    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.

    【讨论】:

      【解决方案2】:

      是的,当applications 更改时,两个段落都会更改。这是由于隐式计算的 observable,它是由敲除创建的。类似于在您的 html 标记中写入:
      &lt;p data-bind="text: 'You have ' + applications() + ' applications'"&gt;&lt;/p&gt;
      在所有三种情况下,淘汰赛都会创建计算出的 observable 并跟踪它依赖于 observable applications。因此,您的“计算”和“经典函数”都会导致隐式计算可观察。正如 XGreen 所指出的,使用计算的正确方法是 text: applicationsText_computed

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        相关资源
        最近更新 更多