Knockout检查推送前是否在observableArray中存在

时间:2015-04-30 01:10:11

标签: javascript knockout.js

我是Knockout的新手,我有一点问题阻止我完成我的简单项目。
我有一个名为 loanDeductions 的observableArray,我在一个带有foreach绑定的表中显示。我有另一个名为 loanDeductionsList 的observableArray,它也来自我的第一个observableArray的json数据,我在我的下拉列表中使用它,当选择一个值时,它将推送所选数据到我的桌子。如果它没有意义,因为我无法清楚地解释它,这是我的javascript文件:

var deductionLine = function (deductionID, deductionName, amount) {
    self = this;
    self.deductionID = ko.observable(deductionID);
    self.deductionName = ko.observable(deductionName);
    self.amount = ko.observable(formatCurrency(amount));
};

function LoanDeductions(deductions) {
    var self = this;
    self.loanDeductions = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
        return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
    }));
    self.loanDeductionsList = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
        return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
    }));

    self.selectedDeduction = ko.observable();

    self.selectedDeduction.subscribe(function (data) {
        self.loanDeductions.push({
            deductionID: data.deductionID,
            deductionName: data.deductionName,
            amount: data.amount,
        });
    });
}

你能帮我找到一种方法让我的函数selectedDeduction.subscribe()仅在我的loanDeductions observableArray中不存在要推送的项目时才推送数据。
任何帮助将不胜感激。谢谢!



我有点意识到我填充下拉列表的方式可能不是最好的方法,我愿意建议更好的方法并重写我的程序。

1 个答案:

答案 0 :(得分:2)

只是为了分享我的所作所为我在selectedDeduction.subscribe()中添加了这一行:

self.selectedDeduction.subscribe(function (data) {
        var match = ko.utils.arrayFirst(self.loanDeductions(), function(deduction) {
            return deduction.deductionID() === data.deductionID(); 
        });
        if (match) {
            alert(data.deductionName() + ' already exists!');
        } else {
            self.loanDeductions.push({
                deductionID: data.deductionID,
                deductionName: data.deductionName,
                amount: data.amount,
            });
            }
});