Skip to content

Instantly share code, notes, and snippets.

@gnab
Created November 13, 2012 14:10
Show Gist options
  • Save gnab/4065953 to your computer and use it in GitHub Desktop.
Save gnab/4065953 to your computer and use it in GitHub Desktop.
markRepeated Knockout binding
// markRepeated binding works on table cell (TD) elements.
//
// If binding value is true, it will check if the current table cell
// has the same text as the previous one to its left.
// If so, the current table cell will be assigned the CSS class "repeated".
//
// Note: binding should be positioned after any "text" or "css" binding, in
// order for text and css to
//
// Example:
// <tr>
// <td data-bind="text: '1', markRepeated: true"></td>
// <td data-bind="text: '1', markRepeated: true"></td> <!-- This will get class="repeated", which can be styled appropriately
// <td data-bind="text: '2', markRepeated: true"></td>
// ...
ko.bindingHandlers.markRepeated = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
$element = $(element),
$previousElement = $element.prev();
if (!$element.is('td') || !$previousElement.is('td')) {
return;
}
$element.removeClass('repeated');
if (value) {
if ($previousElement.text() === $element.text()) {
$element.addClass('repeated');
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment