3
votes

I am so confused by ko.computed. not sure when to use it. I have 2 statements. Can you please explain to me whats the difference and when to use them ?

self.fullName = ko.computed(function() {
    return self.firstName() + " " + self.lastName();
});


self.fullName = function() {
    return self.firstName() + " " + self.lastName();
};
2

2 Answers

5
votes

For displaying a fullName, either of those options will result in the same thing. What makes computed a better difference to a function is that you can assign a read and write sub function. That way you can change the observables with the computed value instead of a seperate function.

In the fiddle, you can see if you change firstName or lastName, both will change. But if you change the computed First or Last name it will change that one and the function as well.

Also, see the computed documentation for more examples.

0
votes

The difference is that when you use ko.computed, if you bind to fullName, fullName will automagically be updated whenever either firstName or lastName changes. Without ko.computed, you'd have to do that work yourself.