[英]Knockout Check If Existing in observableArray before Push
I am new to Knockout and I have a little problem stopping me from completing my simple project. 我是Knockout的新手,我遇到了一个小问题,无法完成简单的项目。
I have an observableArray called loanDeductions that I display in a table with foreach binding. 我有一个名为loanDeductions的observableArray ,它在带有foreach绑定的表中显示。
I have another observableArray called loanDeductionsList which is also from the json data of my first observableArray, I used it in my drop down list which when a value is selected, it will push the selected data to my table. 我有另一个名为loanDeductionsList的observableArray ,它也来自我的第一个observableArray的json数据,我在下拉列表中使用了它,当选择了一个值时,它将把选定的数据推送到我的表中。 If it didn't make sense as I cannot really explain it clearly, this is my javascript file: 如果由于我无法真正清楚地解释它而没有意义,这是我的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,
});
});
}
Can you help me find a way to make my function selectedDeduction.subscribe() push the data ONLY when the item to be pushed is not existing in my loanDeductions observableArray. 您能帮我找到一种方法来使我的函数selectedDeduction.subscribe()仅在我的loanDeductions observableArray中不存在要推送的项目时才推送数据。
Any help will be greatly appreciated. 任何帮助将不胜感激。 Thank you! 谢谢!
I am somewhat aware that the way I populate my dropdown list may o may not be the best way to do it, I am open to suggestion of a better way and rewrite my program. 我有点知道,填充下拉列表的方式可能不是最好的方式,我愿意提出一种更好的方式并重写程序。
just to share what I did I added this line in my selectedDeduction.subscribe(): 只是为了分享我所做的事情,我在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,
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.