0

这个问题在这里 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>

如何让选择更新?

4

1 回答 1

1

您正在重新评估destinations新的observabelArray而不是更新数组。看到这个小提琴。更新任何observable 时,始终将新值作为参数传入,切勿向=操作员分配新值。

错误道:

updateDestinations = function(){
    destinations=ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};

正确的方法:

updateDestinations = function(){
    destinations(mapDictionaryToArray(updatedDestinationsFromServer));
};
于 2013-04-05T16:32:14.330 回答