0

我有一个关于敲除的问题,这是我的 HTML 和 Javascript 代码,你能告诉我我的代码有什么问题吗,当我点击复选框时,相关的 isWaived 未选中

<input type="checkbox" data-bind="checked: isWaived(0)">
<div data-bind="visible: isWaived(0)" >
    <div class="alert">
        You have waived coverage for this member0.
    </div>
</div> 

这是我的 javascript 代码

    function Member(idx, isWaived) {
        var self = this;
        self.idx = idx;
         self.isWaived = ko.observable(isWaived);

    }

    function ReviewCartViewModel() {
        var self = this;
        // Editable data


        self.members = ko.observableArray([
            new Member(0, true),
            new Member(1, false),
            new Member(2, false),
            new Member(3, false),
        ]);

        self.isWaived = function (idx) {
            for (var i in self.members()) {
                var member = self.members()[i];
                if (member.idx == idx)
                    return member.isWaived();
            }
        };

        self.DoWave = function (idxs) {
            for (var i in self.members()) {
                var member = self.members()[i];
                if (member.idx == idxs) {
                    member.isWaived(!member.isWaived());
                    //Send Ajax Request to waived the user
                }
            }
        };
    }

    ko.applyBindings(new ReviewCartViewModel());

这是这个脚本的小提琴页面 http://jsfiddle.net/mohsenvafa/spMvd/

4

2 回答 2

0

您的 javascript 可能有点过度设计。使用正确的绑定,您可以从根模型中删除 isWaived 和 DoWave 函数。这是一个工作解决方案的jsfiddle。

HTML

<!-- ko with:members()[0] -->
<div>
    <input type="checkbox" data-bind="checked:isWaived" />
</div>        
<div data-bind="visible:isWaived">
    <div class="alert">
        You have waived coverage for this member <span data-bind="text:idx"></span>.
    </div>
</div> 
<!-- /ko -->

Javascript

function Member(idx, isWaived) {
    var self = this;
    self.idx = idx;
    self.isWaived = ko.observable(isWaived);    
}

function ReviewCartViewModel() {
    var self = this;
    // Editable data   

    self.members = ko.observableArray([
        new Member(0, true),
        new Member(1, false),
        new Member(2, false),
        new Member(3, false),
    ]);
}

ko.applyBindings(new ReviewCartViewModel());
于 2013-05-23T23:28:16.470 回答
0

将您的绑定(checked单选按钮上的绑定和visiblediv 上的按钮)替换为:

members()[0].isWaived

问题在于,虽然 Knockout 可以从 value中读取isWaived(0),但它不能写入该 value,因为它是评估函数的结果——它不是可观察的。这里我们想要的 observable 是 的isWaived属性,Member上面的语法就是你如何将它交给 Knockout。

于 2013-05-23T21:34:51.647 回答