我只是在学习knockout.js。经过大量的工作,我得到了这个小型的viewmodel,但是ViewModel的shouldBeEnabled方法看起来很笨重。有没有更好的方法来绑定它?
我想要实现的是,如果选择了第一项,则用户无法选择第三项,反之亦然(如果用户选择了第3项,则用户无法选择第一项。)
请参阅此fiddle
<input type="checkbox" data-bind=" enable: shouldBeEnabled(reportType9, 9), checked: reportType9 " />Check 1
<br />
<input type="checkbox" data-bind=" enable: shouldBeEnabled(reportType11, 11), checked: reportType11" />Check 2
<br />
<input type="checkbox" data-bind=" enable: shouldBeEnabled(reportType12, 12), checked: reportType12" />Check 3
function ViewModel() {
var self = this;
self.reportType9 = ko.observable(false);
self.reportType11 = ko.observable(false);
self.reportType12 = ko.observable(false);
self.shouldBeEnabled = function (isChecked, id) {
switch (id) {
case 9:
if (isChecked()) {
self.reportType12();
return true;
}
else {
if (self.reportType12()) {
return false;
}
}
return true;
break;
case 12:
if (isChecked()) {
self.reportType9();
return true;
}
else {
if (self.reportType9()) {
return false;
}
}
return true;
default:
return true;
}
};
}
$(function () {
ko.applyBindings(new ViewModel());
})
答案 0 :(得分:4)
如果您想让逻辑不在您的视野范围内,您还可以使用computed
s。
function ViewModel() {
var self = this;
self.reportType9 = ko.observable(false);
self.reportType11 = ko.observable(false);
self.reportType12 = ko.observable(false);
self.reportType9Enabled = ko.computed(function () {
return !self.reportType12();
});
self.reportType11Enabled = ko.computed(function () {
return true;
});
self.reportType12Enabled = ko.computed(function () {
return !self.reportType9();
});
}
ko.applyBindings(new ViewModel());
查看...
<input type="checkbox" data-bind=" enable: reportType9Enabled, checked: reportType9 " />Check 1
<br />
<input type="checkbox" data-bind=" enable: reportType11Enabled, checked: reportType11" />Check 2
<br />
<input type="checkbox" data-bind=" enable: reportType12Enabled, checked: reportType12" />Check 3
答案 1 :(得分:1)
您可以将逻辑放在视图中:
enable: reportType12() === false
<强> Live demo (click). 强>
通用示例: Live demo (click).
<input
type="checkbox"
data-bind="enable: check2() === false, checked: check1"
>
<label>Check 1</label>
<input
type="checkbox"
data-bind=" enable: check1() === false, checked: check2"
>
<label>Check 2</label>