KnockoutJS: computed vs. pureComputed

后端 未结 2 1756
死守一世寂寞
死守一世寂寞 2020-12-29 01:37

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

Can I use pureComputed instead of computed

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 02:34

    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.

提交回复
热议问题