How to calculate the temporary stop calculated by performing several push / remove operations of an array

I have computedone that is based on a property observableArray headers. I also have methods for adding and removing multiple headers:

function ViewModel() {
    var self = this;

    self.headers = ko.observableArray();
    self.newHeaders = ko.computed(function() {
        var countOfNew = 0;
        ko.arrayForEach(self.headers(), function(header) {
            if (!header.id) {
                countOfNew++;
            }
        });
        return countOfNew;
    });

    self.addHeaders = function(headers) {
        ko.arrayForEach(headers, function(header) { 
            self.headers.push(header);
        }
    };

    self.removeHeaders = function(headers) {
        ko.arrayForEach(headers, function(header) { 
            self.headers.remove(header);
        }
    };
}

When I call addHeadersor removeHeaders, newHeadersis called for every element in the array headers. Is there any solution on how a temporary stop calculates the computed field? (e.g. ko.valueWillMutate, ko.valueHasMutatedused to subscribers).

+4
source share
3 answers

From Knockout.js Gotcha Performance # 2 - Manipulating Observed Arrays

- , , .valueHasMutated(). , .

jsfiddle example . , 'calling computed object' !.

+3

, . var arr = oarr(), , , oarr(arr).

+1

3.1.0 rateLimit , . :

self.headers = ko.observableArray().extend({rateLimit: 0});

( 3.1.0 [3/3/2014] -.)

If you are only interested in delaying the calculated observable (and not everything that depends on the array), you can apply an expander rateLimitto the calculated observable instead. If you are using Knockout 3.0 or earlier, you can use the expander throttleon the calculated one to achieve a similar result:

self.newHeaders = ko.computed(function() {
    ...
}).extend({throttle: 1});
+1
source

Source: https://habr.com/ru/post/1529799/


All Articles