0
votes

I'm struggling with knockout.js selectedOptions binding.

I fill multiselect with items from observableArray A, choose some, store result in observableArray B. When item gets removed from array A, the B array is not updated.

Is this knockout issue or am I doing something wrong?

HTML code:

<h4>All items:</h4>
<div data-bind="foreach: items">
    <p data-bind="text: name"></p>
    <button data-bind="click: $parent.remove">Remove item</button>
</div>

<select multiple="multiple" data-bind="
    options: items,
    selectedOptions: selectedItems,
    optionsText: 'name',
    optionsCaption: 'Choose one or more...'
"></select>

<h4>Selected items:</h4>
<div data-bind="foreach: selectedItems">
    <p data-bind="text: name"></p>
</div>

Javascript:

var viewModel = {
    items: ko.observableArray([
        { name: "Item 1", id: "1" },
        { name: "Item 2", id: "2" },
        { name: "Item 3", id: "3" }
    ]),
    selectedItems: ko.observableArray(),
    remove: function(item) {
        viewModel.items.remove(item);
    }
}

ko.applyBindings(viewModel);

Here's the fiddle: http://jsfiddle.net/3FYAe/

How to reproduce:

  1. select one or more items in the multiselect field, they appear in the list below ("Selected items")

  2. remove one of the selected items

  3. the selectbox is updated

    4.

    • Expected: "Selected items" is updated
    • Actual: "Selected items" keeps deleted values
1

1 Answers

0
votes

Answering my own question:

The trivial solution would be to remove the item from selectedItems array as well, i. e.

remove: function(item) {
    viewModel.items.remove(item);
    viewModel.selectedItems.remove(item);
}

Updated fiddle: http://jsfiddle.net/3FYAe/1/

However, I would like to find a nicer solution as I'm dealing with many more lists and many more dependencies; this is just a simplified example.