6

選択したオプションオブジェクトを取得したい

    <select data-bind="options: availableCountries,
                       value: selectedCountry, event: { select: onSelect}"></select>


<script type="text/javascript">
    // Constructor for an object with two properties
    var Country = function(name, population) {
        this.countryName = name;
        this.countryPopulation = population;   
    };       

    var viewModel = {
        availableCountries : ko.observableArray([
            new Country("UK", 65000000),
            new Country("USA", 320000000),
            new Country("Sweden", 29000000)
        ]),
        selectedCountry : ko.observable(), // Nothing selected by default
        onSelect: function(){
              console.log(viewModel.selectedCountry)
              // it is showing just an country name and what i what is whole object
              // e.g. { "UK", 65000000 } // that is selected option in selected box

        }

    };
</script>
4

1 に答える 1

16

コントロールにselectイベントを追加する必要はありません。より効率的な方法は、selectedCountry変更をサブスクライブすることです。

viewModel.selectedCountry.subscribe(function (data) {
        console.log(data)
    });

デフォルトで国を選択したくない場合は、 :にoptionsCaptionバインディングを追加する必要があります。data-bind

<select data-bind="options: availableCountries,
                       optionsText: 'countryName',
                       value: selectedCountry,
                       optionsCaption: 'Select...'"></select>

ここに作業中のフィドルがあります:http://jsfiddle.net/vyshniakov/tuMta/1/

于 2013-02-05T11:57:37.850 に答える