Jquery Knockout: ko.computed() vs classic function?

折月煮酒 提交于 2020-01-04 15:28:36

问题


I have a view model

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>

Both paragraphs changes the text when i change applications observable.

Then, what is the difference between using a ko.computed and a classinc function?


回答1:


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.

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

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:


Yes, both paragraphs change, when applications changes. It is due to implicit computed observable, which is created by knockout. It is similar to write in your html markup:
<p data-bind="text: 'You have ' + applications() + ' applications'"></p>
In all three cases knockout creates computed observable and tracks that it depends on observable applications. So both your "computed" and "classic function" lead to implicit computed observable. As XGreen noted the right way to use computed is text: applicationsText_computed.

So in this simple case you can use "classic function". For me, it is simpler to write it in html markup if it is the only place. But there are two important points. The first, as i said, that anyway computed observable is created, explicitly or implicitly. The second is that computed observable has much more functionality. E.g. you can explicitly subscribe to it in your code: applicationsText_computed.subscribe(function(newValue) {...}).
Moreover, you can create observable with explicit read and write accessors. Check the documentation for another things. So computed observable is completely different from just function.



来源:https://stackoverflow.com/questions/16274061/jquery-knockout-ko-computed-vs-classic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!