Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout difference between normal javascript function and a computed

Tags:

knockout.js

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?

like image 292
user380689 Avatar asked Oct 04 '22 03:10

user380689


1 Answers

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:

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

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

like image 171
Jeroen Avatar answered Oct 10 '22 01:10

Jeroen