简体   繁体   English

淘汰赛-手动订阅时如何在observableArray中反映所选项目的更改

[英]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: 我有一个绑定到html select的observableArray:

<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: 我已经订阅了selectedCarin,每当用户从html select中选择一辆车时,它将再次将该项目添加到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. 我在推送到observableArray之后立即放置了一个警报,可以肯定的是,每当我选择一个项目时,长度就会增加1。

However, the html select control did not reflect this change. 但是,html select控件未反映此更改。 It was existing in the observableArray but the display didn't show it. 它存在于observableArray中,但显示未显示。 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. 您不是直接在可观察数组上调用push ,而是在底层数组上调用push ,因此不会向knocout发出有关更改的通知。

To fix it you just need to remove the () from cars() : 为了解决这个问题,你只需要删除()cars()

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

Demo JSFiddle . 演示JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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