简体   繁体   中英

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.

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"

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM