0

我正在使用这个计算,正如您可以想象的那样,当我单击 selectAll 时,所有复选框都被选中(一个接一个)并且我“认为”可以进行优化,因此所有都被检查然后重新评估模型但是我'不确定这是否可能。

self.selectAllExpired = ko.computed({
                    read: function() {
                        return ko.utils.arrayFirst(self.paymentOrdersExpired(), function(order) {
                            return !order.isSelected();
                        }) == null;
                    },
                    write: function(value) {
                        ko.utils.arrayForEach(self.paymentOrdersExpired(), function(order) {
                            order.isSelected(value);
                        });
                    },
                    owner:this
                });
4

2 回答 2

1

对于这种情况,节流将是一个不错的选择:http: //knockoutjs.com/documentation/throttle-extender.html

即使使用.extend({ throttle: 1 })添加到您的计算中,也会在您选中每个框时防止计算触发多个更新。

于 2013-06-19T16:56:19.317 回答
0

这是我用来避免在项目的选择更改时重新检查整个数组的算法:

function getIsAllSelectedComputed(arrayObservable) {
    var unSelectedCount = ko.observable(), arrayVersion = 0;
    function updateSelectedCheck(arrayValue) {
        ++arrayVersion; // Whenever the array changes, increment the version
        var initialUnSelectedCount = 0;
        ko.utils.arrayForEach(arrayValue, function(item) {
            var previousValue = item.isSelected();
            if (!previousValue)
                initialUnSelectedCount++;
            if (!item._isSelectedSubVersion) {
                item.isSelected.subscribe(function(latestValue) {
                    if (item._isSelectedSubVersion === arrayVersion) {
                        // Only update the unSelectedCount if the "truthiness" has changed
                        if (Boolean(previousValue) ^ Boolean(latestValue))
                            unSelectedCount(unSelectedCount() + (latestValue ? -1 : 1));
                        previousValue = latestValue;
                    }
                });
            }
            item._isSelectedSubVersion = arrayVersion;
        });
        unSelectedCount(initialUnSelectedCount);
    }
    updateSelectedCheck(arrayObservable());
    arrayObservable.subscribe(updateSelectedCheck);

    return ko.computed({
        read: function() {
            return (unSelectedCount() === 0);
        },
        write: function(value) {
            ko.utils.arrayForEach(arrayObservable(), function(item) {
                item.isSelected(value);
            });
        }
    });    
}

示例:http: //jsfiddle.net/mbest/ssEqj/

于 2013-06-19T21:58:34.573 回答