簡體   English   中英

在保持視圖模型同步的同時取消選擇帶有淘汰的單選按鈕

[英]Deselecting radio buttons with Knockout while keeping the View Model in synch

我在嘗試實現選中/未選中單選按鈕時遇到問題。 我的單選按鈕是從db源動態創建的。

<tbody data-bind="foreach: attByGroups"

    <-- ko foreach: attributes -->
    <input type="radio" onclick="checkStrenghRadios(this)" data-bind="checked: chkValue, value: 1, attr: { name: 'group' + iAttributeID }"/> 
    <input type="radio" onclick="checkDevRadios(this)" data-bind="checked: chkValue, value: 2, attr: { name: 'group' + iAttributeID }"/>
    <-- /ko -->

</tbody

此輸入收音機在淘汰的foreach循環內,因此通常創建2列,每列30個單選按鈕,其中每個組有2個收音機。

foreach循環(attByGroups)源是從計算出的基因剔除數組創建的,因此,當嘗試使用一種解決方案從中選擇/取消選擇單選按鈕時取消選擇單選按鈕,同時使視圖模型保持同步 ),將調用select / unselect函數因此,單選按鈕永遠不會被選中,因為每次單擊都會被選中和取消選中。 我能夠使用另一個JavaScript函數使單選按鈕選擇/取消選擇,但是一旦取消選中單選按鈕,則不會更新單選按鈕的viewModel。

我的計算函數:

self.attByGroups = ko.computed(function () {
    var result = [], attGroupId, currentGroup, chkValue;

    ko.utils.arrayForEach(self.AttributeList(), function (attObj) {

        chkValue = attObj.iAttributeTypeId;

        if (attObj.iAttributeTypeId == 2)
            ListOfOrigDevRadios.push(attObj.iAttributeID);

        if (attObj.strAttributeGroupID !== attGroupId) {
            attGroupId = attObj.strAttributeGroupID;

            currentGroup = {
                groupHeader: attObj.strAttributeGroup,
                //checkValue: chkValue,
                attributes: []
            }

            result.push(currentGroup);
        }

       attObj.chkValue = ko.observable(chkValue);
       currentGroup.attributes.push(attObj);
    })
    self.ProssRadioBtns();
    return result;
});

您可以通過不完全使用“選中的”綁定來獲得所需的東西,這是相當不錯的。 通過綁定到只讀計算變量,可以確保控制底層變量的設置時間,如下所示。

   //stop writes from checked binding
   attObj.compVal = ko.computed({
        read:function(){
            return attObj.chkValue();
        }
    });

標記

 <input type="radio" data-bind="value: 1,checked: compVal, attr: { name: 'group' + iAttributeID },click:toggle"/> 

檢查的綁定只能讀取而不分配給“ chkValue”。 那么下面的代碼將負責確定“ chkValue”,並決定當未選中單選按鈕時會發生什么。

//handle updateing the viewModel on click
        attObj.toggle=function(vm,e){
            //if the value of the element is same as the value of the binding
            //change the checked value to 0 to unselect
            if($(e.srcElement).val()==attObj.chkValue())
                attObj.chkValue(0);
            else
                attObj.chkValue($(e.srcElement).val());

            return true;
        };

我創建了一個jsfiddle來演示我的解決方案https://jsfiddle.net/he80g8xg/6/ ,希望這對您的問題有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM