这个问题在这里 KnockoutJS - Databind to a dictionary collection
我正在从来自服务器的 JSON 创建一个下拉选择。但是在创建它之后的某个时候,我希望更新数据。我创建了一个小提琴 http://jsfiddle.net/LPrf3/
这显示了我目前的位置。我成功更新了选择的可观察数组。但是...由于某种原因,您需要单击下拉菜单中的选择以使其刷新
Javascript:
$(function() {
var destinationsFromServer = {"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"};
var updatedDestinationsFromServer = {"Arctic":"Includes Polar bears and seals","Antarctic":"Just Penguins"};
function mapDictionaryToArray(dictionary) {
var result = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
result.push({ key: key, value: dictionary[key] });
}
}
return result;
}
function viewModel () {
destinations= ko.observableArray(mapDictionaryToArray(destinationsFromServer));
selectedDestination= ko.observable();
updateDestinations = function()
{
destinations= ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};
};
ko.applyBindings(new viewModel());
});
HTML
<select data-bind="options: destinations, optionsText: 'key', optionsValue: 'value', value: selectedDestination"></select>
<hr />
<div data-bind="text: selectedDestination"></div>
<button data-bind="click:updateDestinations">UPDATE</button>
如何让选择更新?