简体   繁体   中英

Knockout - How to reflect changes of selected item in an observableArray when manually subscribing

I have an observableArray that is bound to an html select:

<select name="cars-list" data-bind="options: cars, optionsText: 'name', optionsValue: 'id', value: selectedCar"></select>

I have subscribed to selectedCarin which whenever a user selects a car from the html select, it will add that item again to the select:

self.selectedCar.subscribe(function (newValue) {

    self.cars().push({
        id: 124,
        name: "sample"
    });
});

I placed an alert right after the push to the observableArray and sure enough, the length increased by 1 whenever I select an item.

However, the html select control did not reflect this change. It was existing in the observableArray but the display didn't show it. Any ideas?

You are not calling push directly on the observable array but on the underlaying array, so knocout won't be notified about the change.

To fix it you just need to remove the () from cars() :

self.cars.push({
    id: 124,
    name: "sample"
});

Demo JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM