1

我想获取可观察数组中的值并将它们显示在下拉列表中,但是我不希望下拉列表中的值随着可观察数组的变化而更新?由于其他原因,该数组必须是可观察的。

我知道会有一个简单的方法来做到这一点!

这是一个小提琴来解释我的意思和下面的代码。

视图模型:

ViewModel = function () {
    var self = this;
    self.Owners = ko.observableArray([
        {FullName: 'Bob Jones',Id: 1},
        {FullName: 'Joe Bloggs',Id: 2},
        {FullName: 'Joe Bloggs',Id: 2}
    ]);

    self.GetOwners = function () {
        var ownerIds = [],
            addedIds = [],
            count = 0;

        var owners = ko.utils.arrayForEach(self.Owners(), function (owner) {
            if (addedIds.indexOf(owner.Id) == -1) {
                addedIds[count] = owner.Id;
                ownerIds[count] = {
                    FullName: owner.FullName,
                    Id: owner.Id
                };

                count++;
            }
        });

        return ownerIds;
    }

    self.Add = function() {
        self.Owners.push({ FullName: 'Jane Doe', Id: 3 });
    }
};

var vm = new ViewModel();
ko.applyBindings(vm);

HTML:

<select data-bind="options: GetOwners(), optionsText: 'FullName', optionsValue: 'Id'">    </select>
<!-- I dont want the values in this select to update when I add an owner by clicking the button below -->

<button data-bind="click: Add">Add</button>
4

1 回答 1

4

听起来您应该只对下拉列表中的值使用第二个 observableArray。这样,原始的 observable 就可以在没有影响的情况下发生变化。

于 2013-02-14T02:04:28.673 回答