A simple trick you could use is exploiting a virtual element with a with
binding as such:
HTML:
<!-- ko with: title -->
<h2 data-bind="text: $data"></h2>
<!-- /ko -->
<!-- ko with: summary -->
<h2 data-bind="text: $data"></h2>
<!-- /ko -->
<button type="button" data-bind="click: change">
Change
</button>
JS:
function viewModel() {
var self = this;
this.title = ko.observable('0');
this.summary = ko.observable('0');
this.change = function() {
self.title(Math.random().toString());
if (self.title() < 0.5) {
self.summary(Math.random().toString());
} else {
self.summary(self.summary());
}
}
};
var vm = new viewModel();
ko.applyBindings(vm);
CSS:
h2, p {
animation: bg 1s backwards;
}
@keyframes bg {
0% {
background: #00ff40;
}
100% {
background: initial;
}
}
Complete fiddle
Let's see how it works (this is just a simplified example since you didn't include any additional code):
By wrapping the h2
and p
elements in one-one virtual element to which we apply the with
binding, not the contents of the respective elements (h2
and p
), but the whole elements themselves (that is, the p
and h2
tags in between the comments) get re-rendered whenever the values to which the wrapping virtual elements are bound change.
Since the CSS animation defined is played as soon as the elements to which they apply get (re)created, and because the animation is not repeated, the background of the elements fade from some bright color of your liking into the final background of your choice. (Note that IE might have problems with initial
(see this link), just use the color of your preference in place of it.)
For your convenience, I've added some randomness to the code I've provided. You can see, by clicking enough, that should the value of title
(excuse me for it being a number, wanted to make it as simple as possible) be less than 0.5
, the value of summary
is changed, in which case the background color is animated. If title >= 0.5
, then the value of summary
is not changed - therefore the element is not re-rendered and the animation is not replayed (actually it is changed to the exact same value - I've included it so you can see that even if you pass a value that happens to be the same then no change is fired by knockout).
The downside is that the binding is a little bit dirty because of binding the text content using $data
as value, but if you use it in simple scenarios only it might be a useful timesaver.