What's the difference between computed
and pureComputed
in KnockoutJS?
Can I use pureComputed
instead of computed
safely?
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();
Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.
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.
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.
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.
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