Knockoutjs选择初始值绑定

时间:2012-10-19 06:00:35

标签: knockout.js

我有以下的knockoutjs代码。问题是我希望能够设置selectedCountry变量的值但是要做到这一点我必须将它作为selectedCountry绑定到select元素,但是为了获得初始值,我必须使用这个selectedCountry()代替,因此,当选择其他选项时,我无法更新selectedCountry的值。我该怎么做?

The code is also available here http://jsfiddle.net/xPc9J/

<!doctype html>
<html>
<head>
<script src="knockout-2.1.0.js" type="text/javascript"></script>

</head>
<body>
<p>
    Your country: 
    <select data-bind="options: availableCountries,  optionsValue: 'countryPopulation',optionsText: 'countryName',value: selectedCountry(), optionsCaption: 'Choose...'"></select>
</p>
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
    You have chosen a country with population 
    <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>

<script type="text/javascript">
    // Constructor for an object with two properties
    var country = function(name, population) {
        this.countryName = name;
        this.countryPopulation = population;    
    };        
 var sel=new country("USA", 320000000);
    console.log(sel);
    var viewModel = {
        availableCountries : ko.observableArray([
            new country("UK", 65000000),
            new country("USA", 320000000),
            new country("Sweden", 29000000)
        ]),
        selectedCountry : ko.observable(320000000) // Nothing selected by default
    };
    console.log(viewModel.selectedCountry());
    //viewModel.selectedCountry(sel);
    ko.applyBindings(viewModel);
</script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您的selectedCountry财产保留当前选定的人口而非整体 country

所以你应该写selectedCountry().countryPopulation的所有地方 只需selectedCountry()

<span data-bind="text: selectedCountry"></span>.
<div data-bind="visible: selectedCountry">
    You have chosen a country with population 
    <span data-bind="text: selectedCountry() ? selectedCountry(): 'unknown'">
    </span>.
</div>​

请参阅Fiddle

请注意,()的{​​{1}}绑定中有一组额外的select,因此语法正确无误:

value