46

我有一个使用敲除进行数据绑定的单页应用程序。我的单页应用程序中的 CAApproval.html 视图在视图模型代码中有一个名为 AllCertificates 的可观察数组。它在页面上很好地填充。当您通过单击页面的 navigation.html 部分中的链接离开视图并返回到 CAApproval 页面时,先前访问的值仍在 AllCertificates observableArray 中,因此显示在 CAApproval 视图中。

每次用户返回到使用该 observablearray 的 CAApproval 页面时,我都需要清除 AllCertificates observablearray 的内容,这样如果用户离开页面并返回,则 observablearray 的内容为空,因此不会显示任何数据屏幕。这是我的视图模型代码的亮点-

define(['services/logger', 'durandal/system', 'durandal/plugins/router', 'services/CertificateDataService','controls/Lucas'],

       function(logger, system, router, CertificateDataService) {
        var allCertificates = ko.observableArray([]);

    var activate = function () {
            // go get local data, if we have it
            return SelectAllCerts(),SelectMyCerts(), GetCertificateDetails(), GetDDABankNums();
            };
        var vm = {
            activate: activate,
            allCertificates: allCertificates,
    SelectAllCerts: SelectAllCerts

        });

    return vm;

    function SelectAllCerts() {
                return CertificateDataService.getallCertificates(allCertificates);
        }
    });

每次用户进入该页面时,如何清除 observablearray 的内容(在页面本身内导航时不清除,仅在用户来自单独页面时清除 observablearray)?

4

4 回答 4

84

淘汰赛observableArray也有有趣的方法。呼叫removeAll清除所有项目。
查看官方网站observable array manual

self.mycertificates = ko.observableArray(['C1', 'C2']);  
self.mycertificates.removeAll();
于 2014-01-30T23:59:20.417 回答
44

只需在您的激活函数中将其设置为无(allCertificates([])),每次加载视图模型时都会调用该函数 -

function(logger, system, router, CertificateDataService) {
    var allCertificates = ko.observableArray();

var activate = function () {
    allCertificates([]);
    // go get local data, if we have it
    return SelectAllCerts(),SelectMyCerts(), GetCertificateDetails(), GetDDABankNums();
};

var vm = {
    activate: activate,
    allCertificates: allCertificates,
    SelectAllCerts: SelectAllCerts
});
于 2013-09-05T14:06:28.963 回答
4

对于 Jeremy T(评论空间不足)。
第一个原因,对我来说绝对足够的是,存在用于预期目的的公开可用的 API。

但是要估计性能,您可以检查来源。“observableArray”也是“可观察的”,将附加函数注入到对象中。

所以初始化看起来像这样:

ko.observableArray = function (initialValues) {
    initialValues = initialValues || [];

    if (typeof initialValues != 'object' || !('length' in initialValues))
        throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");

    var result = ko.observable(initialValues);
    ko.utils.extend(result, ko.observableArray['fn']);
    return result.extend({'trackArrayChanges':true});
};

ko.observable = function (initialValue) {
    var _latestValue = initialValue;

    function observable() {
        if (arguments.length > 0) {
            // Write

            // Ignore writes if the value hasn't changed
            if (!observable['equalityComparer'] || !observable['equalityComparer'](_latestValue, arguments[0])) {
                observable.valueWillMutate();
                _latestValue = arguments[0];
                if (DEBUG) observable._latestValue = _latestValue;
                observable.valueHasMutated();
            }
            return this; // Permits chained assignments
        }
        else {
            // Read
            ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
            return _latestValue;
        }
    }
    if (DEBUG) observable._latestValue = _latestValue;
    ko.subscribable.call(observable);
    observable.peek = function() { return _latestValue };
    observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
    observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
    ko.utils.extend(observable, ko.observable['fn']);

    ko.exportProperty(observable, 'peek', observable.peek);
    ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
    ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);

    return observable;
}

并删除所有元素如下所示:

'removeAll': function (arrayOfValues) {
        // If you passed zero args, we remove everything
        if (arrayOfValues === undefined) {
            var underlyingArray = this.peek();
            var allValues = underlyingArray.slice(0);
            this.valueWillMutate();
            underlyingArray.splice(0, underlyingArray.length);
            this.valueHasMutated();
            return allValues;
        }
        // If you passed an arg, we interpret it as an array of entries to remove
        if (!arrayOfValues)
            return [];
        return this['remove'](function (value) {
            return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
        });
    }
于 2014-06-30T20:05:35.167 回答
1

初始化数组变量

self.allCertificates = ko.observableArray([]) 

删除数组的所有值

self.allCertificates.removeAll()
于 2020-04-05T04:54:22.820 回答