Kapil
Kapil

Reputation: 191

Grid value not updating on changing dropdown in Knockout JS

Please find the updated fiddle in the comment section.

I have provided the HTML code and the ViewModel. On changing the value in drop down I want the pip value in grid to be updated. The pip value is getting calculated for new drop down value but the return is not able to bind the value to grid.

Upvotes: 0

Views: 654

Answers (2)

super cool
super cool

Reputation: 6045

well my answer will be addition to what Max Brodin has given .

We can further normalize you code by doing something like this

View model:

    self.dropdownAValue = ko.observable(0.1);

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

    var newItems = ko.utils.arrayMap(self.rates,function(item){
    return new PipCalculation(item, item.price, self.rates, self.newLot[0], self.dropdownAValue)
    });
    self.seats(newItems);

    //computed code
    self.formattedPrice2 = ko.computed(function() {
           //alert("hi");
            var cur = self.rate().pair;
            //var price = self.rate().price;
            //alert(self.myQuote());
            var price = self.myQuote();
            var pip = 1;
            var lot1 =currentlotvalue().lotSize;

Working fiddle here

Things to do :

  • There is no need to additionally write a subscribe for subscribing drop-down changes . All you need to do is send right DD value instance further in your case .
  • There is a performance hit as your are filling observablearray inside DD subscribe i.e every-time dropdown changes . That can be avoided by doing like i mentioned above.
  • Rather pushing into Observable array push into a normal array and the later using that array (performance improved) - max mentioned in his comments

There is a other way to do this like (i done previously like this)

self.seats([]); 
var mutatedArray = self.seats();
ko.utils.arrayForEach(self.rates,function(item){
mutatedArray.push(new PipCalculation(item, item.price, self.rates, self.newLot[0],self.dropdownAValue));  // push to the array(normal array)  
});  
 self.seats.valueHasMutated(); 

For more on this do refer my answer here .

Upvotes: 1

Max Brodin
Max Brodin

Reputation: 3938

In order to make seats change in the UI on dropdownAValue change you need to declare empty observable array first:

self.seats = ko.observableArray();

And update it in the subscribe function instead of creating new observableArray every time:

self.seats([new PipCalculation(self.rates[0], self.rates[0].price, self.rates, self.newLot[0],currentlotvalue) ]);

See updated fiddle

Upvotes: 2

Related Questions