I have ViewModel and one of its properties is an observableArray (receivers). I want to check if an email address already exist to the collection before adding new record to ensure that no duplicate entries will occur. Please help. I tried the approach from here How to conditionally push an item in an observable array? but it's not working. It cannot detect if item to be added with email already on the list. I want that if AddReceiver function is called I will validate the newReceiverData email address. Here's my code.
ViewModel
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
});
}
};
};
I normally use the "any" function in the lightweight underscore.js library for this sort of thing when I work with knockout.
if (!_.any(self.receivers(), function(receiver) { return receiver.receiveremailaddress() == newReceiver.receiveremailaddress(); })) {
// push new receiever
}
You can make the comparison function as simple or as complex as you want.
You could change your self.AddReceiver function to something like this:
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
});
}
}
};
};
This basically flattens your list of receivers to return just the emailAddress, then only adds a new receiver to the array if the email address you're pushing isn't in that list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With