Murali Murugesan
Murali Murugesan

Reputation: 22619

Enable binding with multiple boolean observable flags

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

Answers (2)

Max Brodin
Max Brodin

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

nemesv
nemesv

Reputation: 139798

Because flagA and flagB are observables (which are functions) you need to call them without any argument to get there values if you are using them in an expression:

<input type='text' data-bind='enable: flagA() && !flagB()' />

Demo JSFiddle.

Upvotes: 4

Related Questions