3

我有 ViewModel,它的属性之一是 observableArray(接收器)。我想在添加新记录之前检查集合中是否已经存在电子邮件地址,以确保不会出现重复条目​​。请帮忙。我尝试了这里的方法如何有条件地将项目推送到可观察数组中?但它不起作用。它无法检测要添加的项目是否已经在列表中。我希望如果调用 AddReceiver 函数,我将验证 newReceiverData 电子邮件地址。这是我的代码。

视图模型

var ReceiversViewModel = function () {
    var self = this;
    var errorModal = {};

    self.firstname = ko.observable();
    self.lastname = ko.observable();
    self.receivers = ko.observableArray();
    self.newReceiver = {
        receiverfirstname: ko.observable(''),
        receiverlastname: ko.observable(''),
        receiveremailaddress: ko.observable('')
    };
       self.AddReceiver = function () {
        var newReceiverData = ko.toJS(self.newReceiver);
        if (ReceiverValidate() == true) {
        //check if newReceiverData.receiveremailaddress value already exist
            self.receivers.push({
                EmailAddress: newReceiverData.receiveremailaddress,
                FirstName: newReceiverData.receiverfirstname,
                LastName: newReceiverData.receiverlastname
            });
        }
    }; 
};
4

2 回答 2

3

当我处理淘汰赛时,我通常使用轻量级underscore.js库中的“任何”函数来处理这类事情。

if (!_.any(self.receivers(), function(receiver) { return receiver.receiveremailaddress() == newReceiver.receiveremailaddress(); })) {
            // push new receiever 
        }

您可以根据需要使比较函数变得简单或复杂。

于 2013-05-29T09:59:07.687 回答
1

您可以将 self.AddReceiver 函数更改为如下所示:

self.AddReceiver = function () {
    var newReceiverData = ko.toJS(self.newReceiver);
    if (ReceiverValidate() == true) {

        //get just the email addresses from your receiver collection:
        var emailAddressInReceivers = ko.utils.arrayMap(self.receivers, function (item) {
                item.EmailAddress;
            });

        //only push into array if email address isn't in emailAddressInReceivers
        if (emailAddressInReceivers.indexOf(newReceiverData.receiveremailaddress < 0) {
                self.receivers.push({
                        EmailAddress: newReceiverData.receiveremailaddress,
                        FirstName: newReceiverData.receiverfirstname,
                        LastName: newReceiverData.receiverlastname
                    });
            }
        }
    };
};

这基本上会使您的接收者列表变平以仅返回电子邮件地址,然后仅在您推送的电子邮件地址不在该列表中时将新接收者添加到数组中

于 2013-05-29T09:10:32.353 回答