Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

knockout.js - KnockoutJS: computed vs. pureComputed

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

Can I use pureComputed instead of computed safely?

question from:https://stackoverflow.com/questions/30316954/knockoutjs-computed-vs-purecomputed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...