It seems I can write a function on my view model in two ways with the same result.
Normal javascript function:
vm.Texts = function () {
var self = vm;
if (self.selectedFormat()) {
return self.selectedFormat().Texts();
}
};
ko computed:
vm.Texts = ko.computed(function () {
var self = vm;
if (self.selectedFormat()) {
return self.selectedFormat().Texts();
}
});
'vm' is the view model and selectedFormat is an observable on the view model. In both cases when selectedFormat changes the function is triggered. So my question is what is the difference between the two methods?
I'm supposing a data-binding along these lines:
<span data-bind="text: Texts()"></span>
Bottom line:
In both cases the text binding will create a dependency on selectedFormat on initial rendering.
Details:
Both of your situations will update the span because:
Function case. The text binding will notice on initial rendering that there's a dependency on the selectedFormat observable because it's being called in your function. If the observable ever changes it will find that dependency in KO's registers and trigger an update on the text binding. The dependency looks like this:
text binding --> depends-indirectly-on --> selectedFormat
See this fiddle.
Computed case. The second case may work the same, though it's slightly more obvious, because Texts is now dependent on a (computed) observable that acts as an intermediary to the selectedFormat observable. The dependency is now:
text binding --> depends-on --> Texts computed --> depends-on --> selectedFormat
See this fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With