我有一个绑定到viewmodel的observable属性的复选框,其值为Y或N.我希望在值为Y时检查复选框,在值为N时取消选中。如何实现此?
如果值为0或1但是在Y和N上没有,我能够实现它。在获得值Y或N时,实现所需行为的方法是什么?
复选框代码如下:
<input type="checkbox" data-bind="checked: job.Open" />
答案 0 :(得分:1)
使用computed writable observable:
var ViewModel = function() {
var self = this;
self.actualObservable = ko.observable('Y');
self.relatedObservable = ko.computed({
read: function() { return self.actualObservable() === 'Y'; },
write: function(x) { self.actualObservable(!!x ? 'Y' : 'N'); }
});
};
ko.applyBindings(new ViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: relatedObservable"> = Checked<br />
<i data-bind="text: actualObservable"></i> = Actual
&#13;
您也可以将actualObservable
绑定到复选框,并使计算的observable只读。恕我直言,通常会更有意义,但这取决于你的背景。那个版本看起来像这样:
var ViewModel = function() {
var self = this;
self.actualObservable = ko.observable(true);
self.relatedObservable = ko.computed(function() {
return !!self.actualObservable() ? 'Y' : 'N';
});
};
ko.applyBindings(new ViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: actualObservable"> = Checked<br />
<i data-bind="text: relatedObservable"></i> = Actual
&#13;