选中加载时对象数组中的复选框

Check Checkboxes from an array of objects on load

本文关键字:复选框 数组 加载 对象      更新时间:2023-09-26

>我有这样的模型

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>

现在的问题是,由于选择是对象数组,因此未选中复选框。如何解决此问题?尽管同样的事情适用于只有一个选择的广播。

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

检查绑定未正确比较基元

它还告诉了两种方法。小提琴中提供的解决方案令人毛骨悚然,所以我将使用使用淘汰版 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()),

您需要检查选择的 Id 是否在 AcceptChoices 数组中。使用 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,所以请忽略它。