Phoenix_uy
Phoenix_uy

Reputation: 3294

Perform a not true checked binding on knockout js?

i have an input type checkbox in knockout js and i whant to perform the "not true" action when this checkbox is checked. Something like this:

<input type="checkbox" data-bind="checked: !IsVisible"/> 

But this is not working. I know that i can call IsHidden and set the common checked binding, but i have a special situation in witch i need this behavior.

Upvotes: 2

Views: 2033

Answers (3)

PatrickSteele
PatrickSteele

Reputation: 14697

Define a custom binding. See "Simplifying and cleaning up views in KnockoutJS" which has a section very, very similar to what you're asking for. Basically, something like this should work (NOTE: not tested):

ko.bindingHandlers.notChecked = {
  update: function(element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    ko.bindingHandlers.checked.update(element, function() { return!value; });
  }
};

Then you could do:

data-bind="notChecked: IsVisible"

Upvotes: 5

Joseph Gabriel
Joseph Gabriel

Reputation: 8520

You can evaluate the observable directly in the binding, and your idea should work.

like this: <input type="checkbox" data-bind="checked: !IsVisible()"/>

Note, however, this loses the "observability", which is probably not what you want.

An alternative is to create an IsHidden property that is computed off of IsVisible.

var ViewModel = function (model) {
    var self = this;
    self.IsVisible = ko.observable(model.IsVisible);
    self.IsHidden = ko.computed({
        read: function () {
            return !self.IsVisible();
        },
        write: function (newValue) {
            self.IsVisible(!newValue);
        }
    });
}

See the Fiddle

Upvotes: 3

Chris Dixon
Chris Dixon

Reputation: 9167

It's because with ! you're performing a function on the observable. Use this:

<input type="checkbox" data-bind="checked: !IsVisible()"/> 

Upvotes: 0

Related Questions