how to reapply knockout binding
-
20-06-2021 - |
Pergunta
Currently I have a knockout binding that stripes rows in a list which works fine
ko.bindingHandlers.stripe = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()); //creates the dependency
var allBindings = allBindingsAccessor();
var even = allBindings.evenClass;
var odd = allBindings.oddClass;
//update odd rows
$(element).children(":nth-child(odd)").addClass(odd).removeClass(even);
//update even rows
$(element).children(":nth-child(even)").addClass(even).removeClass(odd); ;
}
}
Triggered from
<button data-bind="click: addWidget" style="display:none">Add Item</button>
The problem I have is when reloading data from the server , I call addWidget() manually in the view model the stripe binding handler is not applied - all rows appear as same color, if I click the html button then the binding happens and stripes appear
var ViewModel = function() {
self.addWidget();
});
Is it possible to reapply this custom binding manually in js?
Thanks
Edit:
The stripe binding gets applied like so
<div data-bind="foreach: widgets, stripe: widgets, evenClass: 'light', oddClass: 'dark'">
Solução
Could you not just use CSS for this? Something like:
div.widget:nth-child(2n) { background: grey; }
Then each row would update regardless of how it got added.
Outras dicas
Zebra effect - a good answer and a working jsfiddle example.
or just use the index var in your foreach loop for your list or table tag element (jsfiddle):
<ul data-bind="foreach: myList">
<li data-bind="css: { 'even': ($index() % 2 == 0) }">
The value is <span data-bind="text: $data"></span>
</li>
</ul>
To obtain a striped effect, you do not need Knockout, use CSS like Tom Hall suggest. However if you insist, here's my take on your problem (assuming you are using ko 2.1.x+):
HTML
<table>
<tbody data-bind="foreach: rows">
<tr data-bind="css: {odd: $index()%2} ">
<td>Test Data</td>
</tr>
</tbody>
</table>
JS
var VM = {
rows: [{},{},{},{},{}]
};
ko.applyBindings(VM);
All you need to do is provide a CSS class .odd
. In case you also want to style the even rows, you can either put a default background-color on <tr>
or provide a .even
class, that's applied to the element with the negated 'odd' condition.
Here's a working Fiddle