Skip to content Skip to sidebar Skip to footer

Jquery Knockout: Ko.computed() Vs Classic Function?

I have a view model function ViewModel() { this.applications = ko.observable(10); this.applicationsText_computed = ko.computed(function () { return 'You have ' + th

Solution 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.

Solution 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.

Post a Comment for "Jquery Knockout: Ko.computed() Vs Classic Function?"