2015-06-22 98 views
1

我有一個複選框綁定到viewmodel的observable屬性,它的值將是Y或N.我希望複選框在值爲Y時進行檢查,並且在值爲N時取消選中。如何做到這一點?複選框被檢查具有值Y

我能夠實現它,如果值是0或1,但不是在Y和N.那麼將有什麼辦法達到預期的行爲有價值Y或N?

複選框代碼如下:

<input type="checkbox" data-bind="checked: job.Open" /> 

回答

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());
<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

你也只是綁定actualObservable的複選框,並計算的可觀察只讀。恕我直言,通常會更有意義,但這取決於你的上下文。該版本是這樣的:

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());
<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