JSFiddle - React, Tailwind, and code Playground
by rniemeyer
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.3.0.js"></script>
<ul data-bind="foreachWithHighlight: items">
<li data-bind="text: $data"></li>
</ul>
<button data-bind="click: addItem">Add Item</button>
JavaScript
ko.bindingHandlers.foreachWithHighlight = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, context);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
var value = ko.unwrap(valueAccessor()),
key = "foreachWithHighlight_initialized";
var newValue = function () {
return {
data: value,
afterAdd: function (el, index, data) {
if (ko.utils.domData.get(element, key)) {
$(el).filter("li")
.animate({
backgroundColor: 'yellow'
}, 200)
.animate({
backgroundColor: 'white'
}, 800);
}
}
};
};
ko.bindingHandlers.foreach.update(element, newValue, allBindingsAccessor, viewModel, context);
//if we have not previously marked this as initialized and there is currently items in the array, then cache on the element that it has been initialized
if (!ko.utils.domData.get(element, key) && value.length) {
ko.utils.domData.set(element, key, true);
}
return { controlsDescendantBindings: true };
}
};
var vm = {
items: ko.observableArray(),
addItem: function() {
this.items.push("new");
}
};
ko.applyBindings(vm);
//add initial items
vm.items(["one", "two", "three"]);