我有一个由“选项”绑定填充的下拉列表,并且希望能够从更改事件的选项列表中检索当前选定的对象。
例如,如果所选选项更改为 UK,我希望能够从 getValue 方法访问 UK Country 对象,如图所示:
var Country = function(name, population, countrytype) {
this.countryName = name;
this.countryPopulation = population;
this.countryType = countrytype;
this.selected = ko.observable( false );
};
var viewModel = {
getValue: function( item ) {
// set selected item's "selected" observable to true and the other items of the same countryType to false
console.log( 'Item: ', item );
},
availableCountries : ko.observableArray([
new Country("UK", 65000000, 'en'),
new Country("USA", 320000000, 'en'),
new Country("Sweden", 29000000, 'sv'),
new Country("Test 1", 29000000, 'sv'),
new Country("Test 2", 29000000, 'de'),
new Country("Test 3", 29000000, 'de')
]),
getByType : function( areaLabel ) {
var results = [];
ko.utils.arrayForEach( this.availableCountries(), function( item ) {
if ( item.countryType === areaLabel ) {
results.push( item );
}
});
return results;
},
selectedCountry : ko.observable() // Nothing selected by default
};
ko.applyBindings(viewModel);
工作示例:http: //jsfiddle.net/dJFLW/4/