我有一个由“options”绑定填充的下拉列表,并希望能够从change事件的选项列表中检索当前选定的对象。
例如,如果所选选项更改为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);
答案 0 :(得分:1)
这就是你想要做的吗? http://jsfiddle.net/dJFLW/3/
如果是这样,您不需要getValue
功能,则可以访问使用selectedCountry
选择的国家/地区。您忘记的是在select HTML元素中设置value
绑定:
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry"></select>
<span data-bind="text: selectedCountry().countryName"></span>
另外,有两件事: