带有敲除数据绑定的复选框在已检查事件上给出错误值

时间:2013-11-05 15:00:15

标签: checkbox knockout.js onchange

<input type="checkbox" data-bind="checked: appealsFromThisCase, event: { change: onappealsFromThisCaseChange}" id="appealsforCaseCheckBox"/>

   vm.onappealsFromThisCaseChange = function () {
        if (vm.appealsFromThisCase())
        {
            vm.predicate(new breeze.Predicate("CaseId", "==", caseID));
            return datacontext.getCaseAppeals().then(function () {
                return true;
            });
        }
        } 
        else
            return vm.getAppeals();

上面是一个复选框,绑定到appealsFromThisCase observable,最初为false。 在更改事件中,onappealsFromThisCaseChange被触发,我看到当取消选中复选框时,observable appealsFromThisCase为true,而当选中复选框时为false。

1 个答案:

答案 0 :(得分:3)

看起来ko以奇怪的方式处理变更事件。小提琴:http://jsfiddle.net/wnLyV/1/

JS:

var VM = function(){
    var self = this;
    self.appealsFromThisCase = ko.observable(false);
    self.appealsFromThisCase.subscribe(function(value){
        console.log("from subscribe: " + value);
    })
    self.onappealsFromThisCaseClick = function(data){
        console.log("from click: " + data.appealsFromThisCase());
        return true;
    }
    self.onappealsFromThisCaseChange = function(data){
        console.log("from change: " + data.appealsFromThisCase());
        return true;
    }    
}


ko.applyBindings(new VM());

另见:

knockout.js and listen to check event on checkbox

Knockout checkbox change event sends old value

您可以使用点击装订或订阅替换更改事件绑定,例如小提琴,还是特别需要更改?

编辑:

因此,根据以下评论,最终答案是:

onappealsFromThisCaseChange函数包装到另一个函数中,该函数将是实际的处理程序并始终返回true。所以只需要创建另一个这样的处理程序:

function(){ 
    onappealsFromThisCaseChange(); 
    return true; 
}