本文介绍了如何使用通用的“非"否定淘汰赛中的isVisible绑定.捆绑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用淘汰赛实现非"绑定?基本上,我想取消绑定值,但保留双向绑定/可观察性.

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.

在我的视图模型中,我有一个属性isVisible,但是我的UI要求要求我提供一个复选框来表示隐藏或不可见"状态.我宁愿不要创建重复属性或第二个属性来跟踪否定状态.

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>

注意:这是一个常见问题解答风格-尽管我发布了答案,但我对任何其他不同的或改进的答案也很感兴趣

推荐答案

这里是一个"not"绑定,可用于任何单参数"bool"类型的绑定,例如checkedvisibleenable等.

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

像这样使用绑定:

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

not绑定:

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.

参见小提琴

这篇关于如何使用通用的“非"否定淘汰赛中的isVisible绑定.捆绑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:13