Search code examples
knockout.jsko.observablearray

knockout + populate value from observable array but dont update value when array updates


I want to get the values in an observable array and display them in a drop-down, however I don't want the values in the drop-down to update as the observable array changes? The array has to be observable for other reasons.

I know there will be an easy way to do this!

Here's a fiddle to explain what I mean and code below.

ViewModel:

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>

Solution

  • It sounds like you should just use a second observableArray for the values in the dropdown. That way the original observable can change without impact.