使用订阅敲除Js复选框验证

时间:2013-11-14 16:17:29

标签: javascript jquery knockout.js

我正在尝试验证是否应该选中复选框,我正在使用订阅,但我不确定为什么它不起作用,我尝试使用文本字段的类似逻辑,它的工作原理。我创建了一个小演示:

<input type ="checkbox" data-bind="checked: IsSelected"/>
<input type ="text" data-bind="value: Name"/>

var model = {
    IsSelected : ko.observable(false), 
    Name: ko.observable("")
}
var demo = 1;
model.IsSelected.subscribe(function(value){
    if (demo == 2 && value){
        model.IsSelected(false);
    }
    demo = 2; 
});
model.Name.subscribe(function(value){
    if (value == "Set"){
        model.Name("Jose");
    }
})
  ko.applyBindings(model);

http://jsfiddle.net/Xepe/9YXTW/

我不确定我做错了什么。

提前致谢。

2 个答案:

答案 0 :(得分:3)

我认为事件会在浏览器更新复选框之前触发,因此即使IsSelectedfalse,它也会查看结果。一种解决方法是使用_.delaysetTimeout延迟将复选框恢复为false:

model.IsSelected.subscribe(function(value){
    if (demo == 2 && value){
        setTimeout(function () { model.IsSelected(false); }, 0);
    }
    demo = 2; 
});

http://jsfiddle.net/9YXTW/17/

答案 1 :(得分:2)

得到应有的尊重,我不知道你要从你的代码中做些什么。然而,根据您的评论:

  

我创建了这个场景,因为我有一个复选框列表,如果选中了其中两个,则不应该选中另一个。

和你的小提琴,我创造了这个:

(Fiddle)

function CheckboxedTextbox(checkboxValue, textboxValue) {
    this.textboxValue = ko.observable(textboxValue);
    this.checkboxValue = ko.computed(function() {
        return this.textboxValue();
    }, this);
    this.isSelected = ko.observable(checkboxValue);
}

function ViewModel() {
    this.checkboxes = ko.observableArray([
        new CheckboxedTextbox(false),
        new CheckboxedTextbox(true, "Default value?"),
        new CheckboxedTextbox(false)
    ]);
    this.valid = ko.computed(function() {
        return this.checkboxes().filter(function(c) {
            return c.isSelected();
        }).length <= 2;
    }, this);
}

ko.applyBindings(new ViewModel());

只会告诉您是否选择了太多。 通知您的用户验证限制可能是一种更好的用户体验模式,而不是自动取消选中他们检查过的框。但是,如果您只想强制立即检查,我会使用更改处理程序,并跟踪最近的更改,将其添加到您的视图模型:

(Fiddle)

    this.lastChangedBox = ko.observable();

    this.forceQuantityChecked = function(newlyChecked) {
        setTimeout(function() {
            if (!this.valid()) {
                this.checkboxes().filter(function(c) {
                    return c.isSelected() && c !== this.lastChangedBox() && c !== newlyChecked;
                }.bind(this)).forEach(function(c) {
                    c.isSelected(false);
                });
            }
            this.lastChangedBox(newlyChecked);
        }.bind(this), 0);
    };

我们确实认为需要setTimeout

最重要的是数据是好的,这就是为什么我们使用observablecomputed s:任何类型的想法,如“是否有太多的复选框被检查”可以表达作为一组互连数据:一个复选框数组,是否选中每个复选框,以及描述框当前状态有效性的属性。

相关问题