user1309226
user1309226

Reputation: 759

With knockout.js how to refresh observable array in a Select element

When the dropdown is loaded the items are populated correctly. But when I click the Refresh button the Dropdown items are not refreshed. The data binding isn't working on clicking the Refresh button. After clicking the Refresh button I am expecting to see 'Mary' and 'Sandra'.

Here's the JavaScript:

        $(function () {

        function viewModel() {
            var self = this;

            self.persons = ko.observableArray([]);
            self.persons.push({
                id: 1,
                name: 'John'
            });
            self.persons.push({
                id: 2,
                name: 'Paul'
            });

            self.refreshPersonList = function () {
                self.persons = ko.observableArray([]);
                self.persons.push({ id: 3, name: 'Mary' });
                self.persons.push({ id: 4, name: 'Sandra' });
            };
        }
        ko.applyBindings(new viewModel());
    });

And HTML:

<select data-bind="options: $root.persons(), optionsValue: 'id', optionsText: 'name'"></select>
    <button value="Refresh" data-bind="event: {click : $root.refreshPersonList() }">Refresh Person List</button>

Upvotes: 0

Views: 1389

Answers (1)

Khan
Khan

Reputation: 18142

Here you are creating a new array, breaking existing bindings:

self.persons = ko.observableArray([]);

Try emptying the array instead:

self.refreshPersonList = function () {
    self.persons.removeAll();  //Empty array
    self.persons.push({ id: 3, name: 'Mary' });
    self.persons.push({ id: 4, name: 'Sandra' });
};

Upvotes: 2

Related Questions