Reputation: 22619
Trying to bind enable state using data-bind based on two flags. We need to enable a input box if flagA
is true and also flagB
is false.
var viewModel = function () {
var self = this;
self.flagA = ko.observable(true);
self.flagB = ko.observable(false);
self.changeState = function () {
self.flagA(false);
}
}
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type='text' data-bind='enable: flagA && !flagB' />
<button data-bind='click:changeState'>changeState</button>
Can any one help me find out why it is not working?
I've tried using a function like enable:function(){flagA && !flagB}
to make this work. But it's not working: it does not observe when I change the state using a button.
Upvotes: 0
Views: 924
Reputation: 3938
Try to avoid putting logic in your views, it's a bad practice. In order to do this add computed
variable
self.isEnabled = ko.computed(function() {
return this.flagA() && !this.flagB()
}, this);
and bind it as usual:
<input type='text' data-bind='enable: isEnabled' />
See fiddle
Upvotes: 3