我有两个多选列表,如果该列表中已存在项目,则可以将项目复制到彼此。问题是复制按钮始终可见。 我只希望当您选择另一个列表中不存在的项目时(按名称比较),该按钮可见。
这有可能吗?
代码:
var SProcsViewModel = function () {
var self = this;
self.storedProceduresInDB1 = ko.observableArray([]);
self.selectedStoredProceduresInDB1 = ko.observableArray();
self.storedProceduresInDB2 = ko.observableArray([]);
self.selectedStoredProceduresInDB2 = ko.observableArray();
self.copyToDb2 = function () {
var sprocs = [];
ko.utils.arrayForEach(self.selectedStoredProceduresInDb1(), function (value) {
var match = ko.utils.arrayFirst(self.storedProceduresInDB2(), function (item) {
return value.Id === item.Id;
});
if (!match) {
sprocs.push(value);
} else {
console.log('Match found for:', value);
}
});
ko.utils.arrayPushAll(self.storedProceduresInDB2, sprocs);
};
populateStoredProceduresInDbB1();
populateStoredProceduresInDbB2();
function populateStoredProceduresInDbB1 () {
var array = [{
Name: "Sp1",
Id: 1,
copyAllowed: false
}, {
Name: "Sp2",
Id: 2,
copyAllowed: false
}, {
Name: "Sp3",
Id: 3,
copyAllowed: true
}, {
Name: "Sp4",
Id: 4,
copyAllowed: true
}];
self.storedProceduresInDB1(array);
};
function populateStoredProceduresInDbB2 () {
var array = [{
Name: "Sp1",
Id: 1,
copyAllowed: false
}, {
Name: "Sp2",
Id: 2,
copyAllowed: false
}, {
Name: "Sp7",
Id: 7,
copyAllowed: true
}, {
Name: "Sp8",
Id: 8,
copyAllowed: true
}];
self.storedProceduresInDB2(array);
};
return self;
};
ko.applyBindings(new SProcsViewModel());
答案 0 :(得分:2)
使用函数确定是否必须显示“复制到DB2”按钮:
self.notExistsInDb2 = function()
{
if (!self.selectedStoredProceduresInDB1().length)
return true;
var chosenNames = self.selectedStoredProceduresInDB1().map(function(i) { return i.Name; });
var existingNames = self.storedProceduresInDB2().map(function(i) { return i.Name; });
for (var i in chosenNames)
if (existingNames.indexOf(chosenNames[i]) > -1) return false;
return true;
};
然后:
<button data-bind="click: copyToDb2, visible: notExistsInDb2()">Copy to DB2</button>