2

Let's say I have a viewModel like this:

function ViewModel() {
    var $t = this;
    this.a = ko.observable(5);
    this.f = function(val) { 
        return $t.a() * (val === 'simple' ? 2: 10);
    };
    this.c = ko.computed(function() { 
        return $t.a() * 20; 
    }); 
};

ko.applyBindings(new ViewModel());

and HTML like this:

<div><input data-bind="value: a"/></div>
<div data-bind="text: f('simple')"></div>
<div data-bind="text: f('complex')"></div>
<div data-bind="text: c"></div>

this results in this initial page (the [5] depicts an input field):

[5]
10
50
100

When I change the 5 in the input field into 10 I see this:

[10]
20
100
200

So the bindings work. See a working demo here: http://jsfiddle.net/1vrz71fs/2/.

What I want to understand is the difference between using ko.computed(...) and a plain old function, they both seem to work just fine. Are there are cons / pros of using the one over the other. The function approach seems to be much more convenient since it accepts parameters which the ko.computed doesn't let me do...

Koen Peters
  • 12,798
  • 6
  • 36
  • 59

1 Answers1

1

In this case, there's no difference because Knockout is creating a computed observable to wrap the function for you. When the value is just something you're going to display in the UI, either way is fine.

It does make a difference when you want to customize the behavior of the observable. For example, rate limiting updates or excluding the value from a server postback aren't possible with the function form. The documentation page for computed observables explains these situations pretty well.

Kevin
  • 8,353
  • 3
  • 37
  • 33