Subscription Knockout Key

I am trying to check if the checkbox should be checked or not, I am using a subscription, but I'm not sure why it does not work, I tried the same logic with a text box and it works. I created a small demo:

<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/

I am not sure that I am doing something wrong.

Thanks in advance.

+4
source share
2 answers

I think the event is fired before the browser updates the checkbox, and thus it ends up viewing, even if IsSelectedthere is one false. One way is to use _.delayor setTimeoutto cancel the checkbox return to false:

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

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

+3

, . , :

, , 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.

, , - , , observable computed s: " " data: , , .

+2

All Articles