1

我有一个这样的模型

function ViewModel(){
    var self = this

    self.Choices            =   ko.observableArray([])
    self.AcceptedChoices    =   ko.observableArray([])

    self.LoadData   =   function(){
        self.ViewAnswered()
    }   

    self.ViewAnswered = function(){
        var url =   'QuestionsApi/ViewAnswered'
        var type    =   'GET'
        ajax(url , null , self.OnViewAnsweredComplete, type )                   
    }
    self.OnViewAnsweredComplete = function(data){
        var currentAnswer = data.Answer

        self.Choices(currentAnswer.Choices)
        self.AcceptedChoices(currentAnswer.AcceptedChoices)
    }       

    self.LoadData()         
}

这是我的对象。我删除了多余的东西

{
    "AcceptedChoices": [94, 95],
    "Choices": [{
        "ChoiceId": 93,
        "ChoiceText": "Never"
    }, {
        "ChoiceId": 94,
        "ChoiceText": "Sometimes"
    }, {
        "ChoiceId": 95,
        "ChoiceText": "Always"
    }]
}

这里有约束力

<u data-bind="foreach:Choices">
    <li>
        <input type="checkbox" name="choice[]" data-bind="value:ChoiceId,checked:$root.AcceptedChoices">
        <span data-bind="text:ChoiceText">Never</span>
    </li>
</u>

现在的问题是,由于选择是对象数组,因此未检查复选框。我该如何解决这个问题?虽然同样的事情适用于只有一个选择的收音机。

4

2 回答 2

2

没关系,我在这里找到了解决方案

已检查的绑定无法正确比较基本体

它还说明了两种方法。小提琴中提供的解决方案令人毛骨悚然,所以我将使用淘汰版 3.0.0 的解决方案。

我需要做的就是附加 knockout-3.0.0.js 而不是任何其他,然后使用checkedValue而不是value.

<input type="checkbox" name="choice[]" 
    data-bind="
            checkedValue:ChoiceId,
            checked:$root.AcceptedChoices"
>

这样就完成了。希望它可以帮助某人。

编辑:

我注意到它不适用于 Chrome。所以我找到了一个替代方案。我创建了这两个函数。

self.ConvertToString = function(accepted){
    var AcceptedChoices =   []
    ko.utils.arrayForEach(accepted, function(item) {
        AcceptedChoices.push(item.toString())
    })  
    return  AcceptedChoices
}
self.ConvertToInteger = function(accepted){
    var AcceptedChoices =   []
    ko.utils.arrayForEach(accepted, function(item) {
        AcceptedChoices.push(parseInt(item))
    })  
    return  AcceptedChoices         
}

并使用它们

self.AcceptedChoices(self.ConvertToString(currentAnswer.AcceptedChoices))

获取价值

AcceptedChoices: self.ConvertToInteger(self.AcceptedChoices()),
于 2013-11-12T10:49:24.930 回答
0

您需要检查选项的 Id 是否在 AcceptedChoices 数组中。使用 ko.utils 数组函数来帮助做到这一点:

checked: function() { return ko.utils.arrayFirst($root.acceptedChoices(), function(item){
    return item == ChoiceId();
} !== null }

您可以将其放入根对象的函数中:

self.isChoiceAccepted = function(choiceId){
    return ko.utils.arrayFirst($root.acceptedChoices(), function(item){
        return item == choiceId;
    } !== null
};

然后在你的数据绑定中调用它:

checked: function() { return $root.isChoiceAccepted(ChoiceId()); }

这没有经过测试,如果 arrayFirst 方法在数组中找不到匹配项,我不能 100% 确定它返回 null,所以请检查一下。

于 2013-11-12T10:41:53.250 回答