Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS: computed vs. pureComputed

What's the difference between computed and pureComputed in KnockoutJS?

Can I use pureComputed instead of computed safely?

like image 934
mehrandvd Avatar asked May 19 '15 04:05

mehrandvd


People also ask

What is Ko pureComputed?

Syntax. The standard method of defining a pure computed observable is to use ko.pureComputed : this .fullName = ko.pureComputed( function () { return this .firstName() + " " + this .lastName();

Which function is used to perform Knockout computation?

Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.

What is Ko applyBindings?

ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

What does Ko unwrap do?

unwrap method is used to read it), the current viewModel and bindingContext. Whenever the passed value changes the binding will print updated information to console. This binding cannot be used with virtual elements (in html comments), only on real elements, since ko.


1 Answers

They are very similar. The difference is that pureComputed has some performance optimizations, and tries to prevent memory leaks, by being smart about who's tracking its changes.

You can safely replace computed with pureComputed in a lot of cases. The function inside the computed should follow this:

1.Evaluating the computed observable should not cause any side effects.

2.The value of the computed observable shouldn’t vary based on the number of evaluations or other “hidden” information. Its value should be based solely on the values of other observables in the application, which for the pure function definition, are considered its parameters.

So as a rule of thumb, any computed observable that just plainly transforms some regular observable properties should be fine as a pureComputed, otherwise stick with computed.

The documentation has decent explanations of when/why you should not use pureComputed observables. Here's a relevant excerpt:

You should not use the pure feature for a computed observable that is meant to perform an action when its dependencies change.

The reason you shouldn’t use a pure computed if the evaluator has important side effects is simply that the evaluator will not run whenever the computed has no active subscribers (and so is sleeping). If it’s important for the evaluator to always run when dependencies change, use a regular computed instead.

like image 188
Jeroen Avatar answered Sep 23 '22 13:09

Jeroen