How to negate the isVisible binding in Knockout using a generic “not” binding?

守給你的承諾、 提交于 2019-12-11 03:09:51

问题


Is is possible to implement a "not" binding using Knockout? Basically, I want to negate the binding value, but retain the two-way binding/observability.

In my view model, I have a property, isVisible, but my UI requirements dictate that I provide a checkbox to represent the hidden, or "not visible" state. I would prefer not to create a duplicate or second property to track the negated state.

Code such as this does not work fully because it does not pass the observable to the binding:

<label>Is Hidden?<input type="checkbox" data-bind="checked: !isVisible()" /></label>

Note: This is a Q&A style question - Although I'm posting an answer, I'm also very interested in any different or improved answers


回答1:


Here's a "not" binding that can be used for any single-parameter "bool" type of binding, such as checked, visible, enable, etc.

Use the binding like this:

<input type="checkbox" data-bind="not: {checked: isVisible}" /> 

The not binding:

ko.bindingHandlers.not = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        //expects a single, truthy/falsy binding, 
        //    such as checked, visible, enable, etc.
        var binding = valueAccessor();
        var observable = binding[Object.keys(binding)[0]];
        var notComputed = ko.computed({
            read: function () {
                return !observable();
            },
            write: function (newValue) {
                observable(!newValue);
            }
        });
        var newBinding = {};
        newBinding[Object.keys(binding)[0]] = notComputed;
        ko.applyBindingsToNode(element, newBinding, viewModel);
    }
};

I haven't really tried to polish the binding, but it seems to be fully functional.

See the Fiddle



来源:https://stackoverflow.com/questions/16368784/how-to-negate-the-isvisible-binding-in-knockout-using-a-generic-not-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!