1

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>

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.