2

現在、ブール値がラジオ ボタンにうまくマッピングされていないことを補うために、次のことを行っています。フィールドがオブザーバブルからどのように読み取られるかが原因で、(true と false ではなく) 1 と 0 を値にバインドすることに行き詰まっています。Pref1/Pref2 の値は、サーバーから true/false ブール値として取得されます。ここで重要なのは、ラジオ ボタンのチェックされた値をデータ バインドしてオブジェクトの true/false に一致させるだけでなく、true/false のブール値を GraduationClass オブジェクトに書き戻すことです。私の補償コードは醜いだけでなく、スケーラブルでもありません。

<input type="radio" value="1" name="radioGroup" data-bind="checked: Pref1" />Yes
<input type="radio" value="0" name="radioGroup" data-bind="checked: Pref2" />No    
<a href="javascript:void(0);" data-bind="click: $root.saveGraduationClass ">Save</a>  

function SiteSettingsViewModel() {
    var self = this;
    this.saveGraduationClass = function(graduationClass) {
        // hack until i get a custom radio button binding
        if (graduationClass.Pref1() == 1) {
            graduationClass.Pref1(true);            
        } else {
            graduationClass.Pref1(false);            
        }  

        if (graduationClass.Pref2() == 1) {
            graduationClass.Pref2(true);
        } else {
            graduationClass.Pref2(false);
        }

        // ...ajax call to save graduationClass to the server
    }

function GraduationClass(data) {
    var self = this;
    ko.mapping.fromJS(data, {}, this);
}
4

1 に答える 1

2

これは、"checked" 属性を持つラジオ ボタンを使用する方法を示す、knockoutJs Web サイトの例です。

<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
    Preferred flavor of spam:
    <div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
    <div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
    <div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>

<script type="text/javascript">
    var viewModel = {
        wantsSpam: ko.observable(true),
        spamFlavor: ko.observable("almond") // Initially selects only the Almond radio button
    };

    // ... then later ...
    viewModel.spamFlavor("msg"); // Now only Monosodium Glutamate is checked
</script>

しかし、1つのラジオボタングループ「radioGroup」に対して「Pref1」と「Pref2」の2つのオブジェクトを使用する理由がわかりませんか? この場合、「spamFlavor」を使用した例のように、1 つのオブジェクトのみを使用できます。

したがって、バインドしたいものをより詳細に記述してください: 1 つのラジオボタンが 1 つの選択された値でグループ化されるか、またはその他の何か。

また、計算されたオブザーバブルを使用してさまざまな値を計算することもできます。を参照してください。

于 2012-06-12T17:46:15.590 に答える