如何在单击时刷新绑定



我正在创建一个带有两个复选框的表单。

如果用户检查复选框1,则应禁用2。如果检查复选框2,则应禁用1个。如果用户取消选中1,则应启用2。如果用户取消选中2,则应启用1。

(我知道这可以使用单选按钮完成,但是实际的用例具有许多可以检查的复选框。此示例仅为简单起见。)

换句话说,基于用户操作,将启用剩余的复选框/禁用。

我在这样的复选框上具有绑定表达式:

<input type="checkbox" onclick="refreshBindings(event)" data-bind="enable: getIsEnabled(1)" value=1>
<input type="checkbox" onclick="refreshBindings(event)" data-bind="enable: getIsEnabled(2)" value=2>

var currentId=0;
functionRefreshBindings(event)
{
    currentId = event.currentTarget.value;
    //How do I get the bindings to reevaluate getIsEnabled() for each item?   
}
function getIsEnabled(id) {
    switch (+id) {
        case 1:
            if(currentId===2)
                return false;
            else return true;
        case 2:
             if(currentId===1)                 
                return false;
             else
                return true;
                }
    return true;
}

那么如何获得刷新的绑定?

在使用基因敲除时,尝试远离使用onclick事件和value属性之类的事物。使用MVVM尝试尽可能依靠数据结合。如果正确绑定,敲除应自动刷新启用状态。

例如,假设此视图:

<input type="checkbox" data-bind="enable: shouldBeEnabled(propA), checked: propA" /> Check 1<br />
<input type="checkbox" data-bind="enable: shouldBeEnabled(propB), checked: propB" /> Check 2<br />
<input type="checkbox" data-bind="enable: shouldBeEnabled(propC), checked: propC" /> Check 3

此ViewModel应该执行您的要求:

function ViewModel(){
    var self = this;   
    self.propA = ko.observable(false);
    self.propB = ko.observable(false);
    self.propC = ko.observable(false);
    self.shouldBeEnabled = function(myVal){
        if (myVal() === true) { return true; }
        return !self.propA() && !self.propB() && !self.propC();
    }
}

请参阅此演示的小提琴。

最新更新