本文介绍了KnockoutJS:计算与pureComputed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

KnockoutJS中的computedpureComputed有什么区别?

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

我可以安全地使用pureComputed代替computed吗?

Can I use pureComputed instead of computed safely?

推荐答案

我同意@Jeroen,并且想补充一下J. Munro的这对我有很大帮助,所以这对其他人也可能有帮助.

I agree with the @Jeroen and I would like to add a short example from J. Munro's book which helped me a lot so this might be helpful for others as well.

首先,pureComputed可观察变量与计算的可观察变量非常相似,但在性能和内存方面有所改进.该名称是从纯函数编程术语中借用的,它意味着任何仅使用局部变量的函数可能是纯函数,而使用非局部变量的任何函数都可能是不纯函数.

First of all, pureComputed observables are quite similar to the computed observables with several performance and memory improvements. The name is borrowed from the Pure function programming term and it means that any function which uses only local variable is potentially pure, whereas any function that uses a non-local variable is potentially impure.

Knockout.js中的可观察对象的处理方式有所不同.因此,将pureComputed可观察对象置于休眠模式(Knockout倾斜所有依赖项并在读取后重新评估内容),并将计算出的Observable置于侦听模式(Knockout在第一次访问之前不断检查值是否为最新). .

The observables in Knockout.js are treated differently. Thus pureComputed observables are placed in a sleeping mode (Knockout inclines all dependencies and re-evaluates the content when after reading) and computed observables are placed into listening mode (Knockout constantly checks whether the value is up-to-date prior to first access).

因此,如果您需要执行其他代码,则最好使用计算的可观察对象.

Therefore, if you need to execute other code, then better to use a computed observables.

function ViewModel() {
     var self = this;

     self.firstName = ko.observable('Arshile');
     self.lastName = ko.observable('Gorky');
     self.pureComputedExecutions = 0;
     self.computedExecutions = 0;

     self.pureComputedFullName = ko.pureComputed(function() {
         // This is NOT recommended
         self.pureComputedExecutions++;
         return 'Hello ' + self.firstName() + ' ' + self.lastName();
     });
     self.computedFullName = ko.computed(function() {
         self.computedExecutions++;

         return 'Hello ' + self.firstName() + ' ' + self.lastName();
     });
 };
 var viewModel = new ViewModel();
 ko.applyBindings(viewModel);

 alert('Pure computed executions: ' + viewModel.pureComputedExecutions);
 alert('Computed executions: ' + viewModel.computedExecutions);

运行此代码时,将显示两条警报消息,其中显示了调用pureComputed和计算函数的次数.由于pureComputed处于睡眠模式,因此该函数从未被访问过,并且计数器将显示0.与此相反,计算的函数在数据绑定时自动求值,导致计数器增加数字并显示1.

When this code is run, two alert messages are displayed that show the number of times the pureComputed and computed functions are called. Since pureComputed is in sleeping mode then the function has never been accessed, and the counter wil display 0. In contrast to this, the computed function is automatically evaluated on data binding, causing the counter to increase the number and display 1.

这篇关于KnockoutJS:计算与pureComputed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:25