15

我有一系列限制,以及启用/禁用限制的复选框。但是复选框不起作用

jsFiddle

function Limit(start, end)
{
    var that = this;

    this.start = start;
    this.end = end;

    this.label = ko.computed(function(){
        return that.start + ' - ' + that.end;            
    });
}

function ViewModel()
{
    var that = this;

    this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];

    this.activeLimit = ko.observable(that.limits[0]);

    this.changeActiveLimit = function(limit)
    {
            that.activeLimit(limit);
    }
}

ko.applyBindings(new ViewModel());​

我的 HTML

<div data-bind="foreach: {data: limits, as: 'limit'}">
 <input type="checkbox" data-bind="click: $root.changeActiveLimit, checked: limit.label == $root.activeLimit().label"/>
    <span data-bind="text: limit.label"/> 

</div>
4

2 回答 2

14

如果您像下面这样修改您的视图模型,它将起作用

function ViewModel()
{
    var that = this;

    this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];

    this.activeLimit = ko.observable(that.limits[0]);

    this.changeActiveLimit = function(limit)
    {
            that.activeLimit(limit);
            return true;
    }
}

return true是这里的关键部分。

这是一个工作小提琴 http://jsfiddle.net/tariqulazam/WtPM9/10/

于 2012-11-25T21:00:06.043 回答
13

关键是返回true;在点击处理函数的末尾!这会正确更新 UI。

于 2013-10-13T10:13:49.893 回答