2

How can I handle a subscribe that would trigger after the dom is updated? I am trying to run some jQuery that updates the even visible rows on a table by giving them a css class of "even". The subscribe function is listening for a change in a property carsOnly, which toggles whether or not just car items should be shown, or if all items should be shown.

Issue: in my subscribe, the jQuery that sets the even rows' CSS gets run before the dom is updated, so it adds "even" class to rows that are then hidden a split second later when the dom does finally update.

Html:

<input type="checkbox" data-bind="checked: carsOnly" /><label>Show cars only</label>
<tbody data-bind="foreach: items">
  <tr data-bind="visible: !viewModel.carsOnly() || isCar()">
    <td data-bind="text: vehicleType"></td> <!-- would display 'car' or 'truck' -->
  </tr>
</tbody>

Js:

var viewModel = ko.mapping.fromJS({
  carsOnly: true,
  items: [{vehicleType:'car'},{vehicleType:'car'},{vehicleType:'truck'}]
});

viewModel.carsOnly.subscribe(function(newVal) {
  // problem is, this fires off _before_ any of the rows in the table are made invisible
  $("tbody tr").removeClass("even");
  $("tbody tr:visible:even").addClass("even");
});

ko.applyBindings(viewModel);

Css:

tbody tr.even { background-color: blue; }
Ian Davis
  • 19,091
  • 30
  • 85
  • 133

1 Answers1

0

personally I would apply a filter in your viewModel to get a list of items to be applied to the DOM. then use the CSS selector tr:nth-child(even) to apply your stripping.

jsFiddle

HTML

<input type="checkbox" data-bind="checked: carsOnly" />
<label>Show cars only</label>
<table>
<tbody data-bind="foreach: filteredItems">
    <tr>
        <td data-bind="text: vehicleType"></td>
        <!-- would display 'car' or 'truck' -->
    </tr>
</tbody>
</table>

JS

var viewModel = ko.mapping.fromJS({
    carsOnly: true,
    items: [{
        vehicleType: 'car'
    }, {
        vehicleType: 'car'
    }, {
        vehicleType: 'truck'
    },{
        vehicleType: 'car'
    }, {
        vehicleType: 'car'
    }, {
        vehicleType: 'truck'
    }]
});
viewModel.filteredItems = ko.computed(function() {
    var filter = this.carsOnly();
    if (!filter) {
        return this.items();
    } else {
        return ko.utils.arrayFilter(this.items(), function(item) {
            return 'car' === item.vehicleType()
        });
    }
}, viewModel);


ko.applyBindings(viewModel);

CSS

tr:nth-child(even) {
  background-color: red;
}


tr:nth-child(odd) {
  background-color: white;
}
Nathan Fisher
  • 7,961
  • 3
  • 47
  • 68