Knockout: computed observable function vs

When using knockout, what is the advantage of using calculated observable data rather than simple functions?

Take the following viewmodel constructor and html snippet, for example:

var ViewModel = function(){ var self = this; self.someProperty = ko.observable("abc"); self.anotherProperty = ko.observable("xyz"); self.someComputedProperty = function(){ return self.someProperty() + self.anotherProperty(); }; }; <input data-bind="value: someProperty"/> <input data-bind="value: anotherProperty"/> <p data-bind="text: someComputedProperty()"></p> 

Everything here seems to work the way you expected, so there is a reason I should use:

 โ€‹var ViewModel = function(){ var self = this; self.someProperty = ko.observable("abc"); self.anotherProperty = ko.observable("xyz"); self.someComputedProperty = ko.computed(function(){ return self.someProperty() + self.anotherProperty(); }); }; <input data-bind="value: someProperty"/> <input data-bind="value: anotherProperty"/> <p data-bind="text: someComputedProperty"></p> 

I noticed that the documentation at http://knockoutjs.com/documentation/computedObservables.html states that "... declarative bindings are just implemented as computed observables", what do I need to use them explicitly in my models?

+52
computed-observable
Jul 17 2018-12-17T00:
source share
1 answer

If the sole purpose of your calculated observable is to make a simple binding to it, then using the function will be equivalent. Bindings are implemented inside the computed observable to track dependencies, so it will restart your binding when any of the observables changes.

Here are a few things to consider regarding computed observables versus function

  • the value of the calculated observable is cached, so it is updated only after it is created and when the dependencies are updated. For a regular function, you will need to execute the logic every time. If many things depend on this value (say, every element in the collection is bound to a value from the parent), then this logic will run again and again.

  • in your JavaScript, you can also use calculated observable data, like other observables. This means that you can create manual subscriptions to them and depend on them on other calculations (calling the function would also create this dependency). You can rely on the usual utility methods in KO, for example ko.utils.unwrapObservable , in the general case to determine whether you need to call it as a function or not retrieve the value.

  • if in the end you want to send a value to the server, the calculated observable will naturally appear on your JSON output, and the value resulting from the normal function will simply disappear when converted to JSON (you should do more work to fill the property from this function first) .

+70
Jul 17 2018-12-17T00:
source share



All Articles