Reputation: 11721
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?
Upvotes: 2
Views: 960
Reputation: 11558
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
Upvotes: 7
Reputation: 7475
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.
Upvotes: 2