2012-10-19 122 views
2

我有以下knockoutjs代碼。問題是,我想能夠設置selectedCountry變量的值,但要做到這一點,我必須將它作爲selectedCountry綁定到select元素,但是爲了獲得初始值,我必須使用此selectedCountry()來代替,因此當選擇另一個選項時,無法更新selectedCountry的值。我如何去做這件事?Knockoutjs選擇初始值綁定

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> 

回答

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

注意你在selectvalue綁定,所以正確的語法有一個額外的一套()是:

value: selectedCountry