使用从服务器接收的JSON数据更新视图模型时刷新Knockout绑定

时间:2014-03-26 20:38:36

标签: knockout.js

我有一个knockout viewmodel,它使用从服务器收到的每个按钮点击的JSON数据进行更新,并希望根据对viewModel的更改刷新绑定。我正在使用knockout映射将JSON转换为KO observables。

我的问题是,在点击按钮

上更新视图模型时,不会刷新绑定

样本小提琴是here

JS:

    function getPlayersAsJSON(country) {
    var players = null;
    if (country === 'spain') {
        players = $('#spainText').val();
    } else if (country === 'swiss') {
        players = $('#swissText').val();
    }
    return players;
}

var viewModel = {
    players: ko.observableArray()
};

$(function () {
    $('#btnSearch').click(function () {
        var playerDataJSON = getPlayersAsJSON($('#drpCountry').val());
        var playerData = ko.mapping.fromJSON(playerDataJSON);
        console.log(playerDataJSON);
        console.log(playerData);
        console.log(playerData());
        viewModel.players(playerDataJSON);
    });
});

ko.applyBindings(viewModel);

HTML:

    <div>JSON Data for Spain
    <br/>
    <textArea id="spainText" rows="4" cols="50">[{"Name": "Nadal","Age": 28},{"Name": "Ferrer","Age": 32},{"Name": "Ferrer", "Age": 29}]</textArea>
    <br/>JSON Data for Swiss
    <br/>
    <textArea id="swissText" rows="4" cols="50">[{"Name": "Federer","Age": 32},{"Name": "Wawiranka", "Age": 28}]</textArea>
</div>
<br/>
<div>Select Country
    <br/>
    <select id="drpCountry">
        <option value="spain">spain</option>
        <option value="swiss">swiss</option>
    </select>
</div>
<input type="button" id="btnSearch" value="Search" />
<br/>
<table>
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: players">
        <tr>
            <td data-bind="text: $data.Name"></td>
            <td data-bind="text: $data.Age"></td>
        </tr>
    </tbody>
</table>

如果您需要更多详细信息,请与我们联系

1 个答案:

答案 0 :(得分:2)

如果输入是数组,则ko.mapping.fromJSON将返回ko.observableArray

因此,您需要编写playerData()来解包可观察数组,否则您将结束持有另一个可观察数组的players可观察数组:

var playerData = ko.mapping.fromJSON(playerDataJSON);
viewModel.players(playerData()); //unwrap the playerData 

演示JSFiddle

作为替代解决方案,如果输入是JSON数组,映射插件支持直接填充已存在的可观察数组,语法如下:

ko.mapping.fromJSON(playerDataJSON, {} /* empty options */, viewModel.players);

演示JSFiddle