简体   繁体   中英

Updating values from select list with Knockout.js

I was trying to modify the lists and collections tutorial found on the knockout.js website by allowing an editable price rather than a fixed value.

Right now the lists and data populate correctly when the page loads. However, if I select a new value from the list the price and id do not change for that row. The total surcharge changes, but the row itself doesn't. Also, if I change the price manually for a given row, the total surcharge doesn't change.

I tried setting the individual values to observables such as shown below, but the price and id values still don't update when a new list item is selected, only the total surcharge

function RowReservation(initialRow) {
    var self = this;

    self.row = ko.observable(initialRow);
    self.rowID = ko.observable(self.row().rowID);
    self.price = ko.observable(self.row().price);
}

So the two issues I can't seem to figure out

  1. When a new item is selected in the list, the corresponding price and id do not change

  2. If a price is manually changed, the total surcharge doesn't update

EDIT - Number 1 of my list has been fixed, and 2 partially has.

If I change a price in one of the text boxes for either row, the total surcharge will ONLY update if another row is added or the other row's name has been changed. Basically, it's not an immediate change, it's only computed when a new value is introduced. How can I make it so it updates automatically? Is there a way to subscribe to the price textboxes?**

Here is an updated fiddle

The only thing you need to modify in your code is this part in line 17 of your HTML

<input data-bind="value: price" />

into

<input data-bind="value: $data.row().price"/>

When you bind the 'price' initially, you were binding it to the price attribute of RowReservation object. When the 'row' value changed, the value of 'price' attribute was not updated. Therefore it still shows the original price.

I changed the binding so that it is showing the price attribute of 'row'. So when 'row' is changed by selecting different item in the combobox, the price is updated to the price of the newly selected row.

Basically you have

// RowReservationObject

{'row': 
    {'rowName': 'Standard',
     'rowID': 1, 
    'price': 19.99 },   // --> this is what I'm binding against now
'rowID': 1 
'price': 19.99}  // -- this is what you were binding against before

If you change the variable names a bit it might become clearer to you. I hope I'm making sense.

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