如何通过Select元素更新Observable Array的值

时间:2014-03-05 22:46:11

标签: javascript knockout.js

我有一个可观察的数组,我在一个选择元素中显示,例如,如果我在数组中有4个元素,那么我将有4个选择元素。

当我更改Select列表中的项目时,可观察数组似乎没有变化。

请帮助我了解如何更新可观察数组。

相同的jsfiddle是here

HTML代码

    <div>
    <div>
        <table>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
            <tbody data-bind="foreach: players">
                <tr>
                    <td data-bind="text: name"></td>
                    <td data-bind="text: age"></td>
                    <td data-bind="text: country"></td>
                    <td data-bind="text: trophies"></td>
                    <td>
                        <button data-bind="click: $root.editPlayers">Edit</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div data-bind="with: editPlayer">
         <h3>Edit</h3>
Name:
        <input type="text" data-bind="value: name" />
        <br/>Age:
        <input type="text" data-bind="value: age" />
        <br/>Country:
        <input type="text" data-bind="value: country" />
        <span data-bind="foreach: trophies">
            <br/>Tropies:
            <select data-bind="options: $root.trophiesList, value:$data, optionsCaption:'Choose..'"></select>    
        </span>

    </div>
</div>

JavaScript代码

    var player = function (name, age, country, trophyArray) {
    this.name = ko.observable(name);
    this.age = ko.observable(age);
    this.country = ko.observable(country);
    this.trophies = ko.observableArray(trophyArray);
};

var playerModel = function () {
    var self = this;
    self.players = [
        new player('Roger', 32, 'swiss', ['AO','FO','WB','US']),
        new player('Murray', 28, 'Scott', ['WB','US'])];

    self.editPlayer = ko.observable();
    self.trophiesList = ['AO','US','FO', 'WB'];

    self.editPlayers = function (player) {
        self.editPlayer(player);
    }

}

ko.applyBindings(new playerModel());

2 个答案:

答案 0 :(得分:1)

删除以下标记:

<span data-bind="foreach: trophies">  以及结束</span>标记。

然后使用selectedOptions绑定来管理奖杯阵列:

    <br/>Tropies:
    <select data-bind="options: $root.trophiesList, selectedOptions:trophies, optionsCaption:'Choose..'" multiple="true" size="10"></select>    

然后,用户可以选择/取消选择多个奖杯。

答案 1 :(得分:0)

您好我为您创建了一个更新的小提琴

self.players = [
    new player('Roger', 32, 'swiss', [{key: ko.observable('AO')},{key:ko.observable('FO')},{key:ko.observable('WB')},{key: ko.observable('US')}]),
    new player('Roger', 32, 'swiss', [{key: ko.observable('AO')},{key:ko.observable('FO')},{key:ko.observable('WB')},{key: ko.observable('US')}])];

http://jsfiddle.net/M8m8R/4/

希望这有帮助