Highlight when a value changes

33 views
Skip to first unread message

Bill Tindal

unread,
Jun 7, 2016, 10:19:48 PM6/7/16
to KnockoutJS
Hi,

Question: How can I create a highlight on the 'stock' table cell whenever the value within changes?

I have the following setup (altered to provide an example):

// this is updated via ajax periodically
self.items = ko.observableArray([]);


self.sortedCart = ko.pureComputed(function () {
 
var cart = setup.cart.map(function (itemId) {
 
var i = ko.utils.arrayFirst(self.items(), function (item) {
 
return item.id === parseInt(itemId);
 
});
 
return {
 sku
: i.sku,
 name
: i.name,
 quantity
: i.quantity,
 stock
: i.stock,
 price
: i.price
 
};
 
});
 
return cart;
});


//HTML


<table>
<thead>
 
<tr>
 
<th></th>
 <th></
th>
 
<th></th>
 </
tr>
</thead>
<tbody data-bind="forEach: sortedCart">
 <tr>
 <td data-bind="text:name"></
td>
 
<td data-bind="text:quantity"></td>
 
<td data-bind="text:stock"></td>
 
</tr>
</
tbody>
</table>


Any help would be much appreciated.

noirabys

unread,
Jun 9, 2016, 5:43:27 AM6/9/16
to KnockoutJS
hi,
i would solve this adding more object orientation to it :

1. class which manages the stock , find entry call init with new data or add new entry if not found
2. class which represents a stock entry:

function StockEntry(data){
  var self = this,


   self.name = ko.observable();
   self.quantity = ko.observable();
   self.stock = ko.observable();
   self.stockChanged = ko.observable(false);

   self.init = function(data){
        self.name(data.name);
        self.quantity(data.quantity );
        self.stock(data.stock);
   }

   this.stock.subscribe(function(newVal){
       this.stockChaged(true);
       // perhaps setTimeout to reset value
  });

  self.init(data);      
}



<style>
  .highlighted {background-color:#yellow;}
</style>
<table>
<thead>
 
<tr>
 
<th></th>
 <th></
th>
 
<th></th>
 </
tr>
</thead>
<tbody data-bind="forEach: sortedCart">
 <tr>
 <td data-bind="text:name"></
td>
 
<td data-bind="text:quantity"></td>

 
<td data-bind="text:stock(), css:{ 'highligted': stockChanged() }"></td>
 
</tr>
</
tbody>
</table>

best regards,
noirabys
Reply all
Reply to author
Forward
0 new messages