如何计算复选框和subribe的初始状态,以便在淘汰赛中更新状态更改

时间:2015-09-08 07:48:56

标签: knockout.js

我想根据计算值检查/取消选中初始页面加载中的复选框。稍后,当用户选中/取消选中我想要捕获的复选框时。

 <div class="col-sm-9 col-md-9 pull-right">
        <input type="checkbox" class="control-label" data-bind="checked:IsGroup" />
        <label class="control-label form-label" style="text-align:center;vertical-align:middle">Medical Group</label>
    </div>
self.IsGroup = ko.computed(function () {
        return someValue == null ? false : true;
    });

self.IsGroup .subscribe(function (newValue) {
        if (newValue) {

            alert(newValue);
        }
        else {
            alert(newValue);
        }
    });

订阅事件未触发。如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

您计算了只读。让它像这样可写:

self.IsGroup = ko.computed({
    read: function () {
        return someValue == null ? false : true;
    },
    write: function(newValue) {
        someValue = newValue;
        alert(newValue);
    }
});

请注意,这实际上意味着您不需要订阅:您可以在alert功能中触发自定义逻辑(例如write)。这正是可写计算的好处。

有关详细信息,请参阅the official computed documentation