【问题标题】:KnockoutJS - Databind to a dictionary collection - with updateKnockoutJS - 数据绑定到字典集合 - 更新
【发布时间】:2013-04-05 16:15:38
【问题描述】:

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

如何让选择更新?

【问题讨论】:

    标签: json knockout.js


    【解决方案1】:

    您将destinations 重新评估为新的observabelArray,而不是更新数组。见this fiddle。更新 any 可观察对象时,始终将新值作为参数传入,切勿使用 = 运算符分配新值。

    错误的方式:

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

    正道:

    updateDestinations = function(){
        destinations(mapDictionaryToArray(updatedDestinationsFromServer));
    };
    

    【讨论】:

    • 成功了……终于成功了! :D 你知道烦人的是我已经知道了。然而,我花了一些时间才找到地图字典数组解决方案,到那时,在盯着同一件事大约 12 小时后,我的思绪变成了果冻……非常感谢!
    猜你喜欢
    • 2011-11-16
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多