Declarative chaining of knockout.js animations?
knockout.js
Solution
This approach creates a computed observable that looks to the boolean observable to determine which text to display.
Here's a working jsfiddle. http://jsfiddle.net/yq5rS/10/
And here's a quick idea of the code
Html
<div class='liveExample'>
<p>
<label>
<input type='checkbox' data-bind='checked: display' />
Active?
</label>
</p>
<p data-bind='fadeVisible: IsActive()'></p>
</div>
Scripts
var Model = function() {
var self = this;
self.display= ko.observable(false);
self.IsActive = ko.computed(function() {
if (self.display()) return "Active."
return "Not active."
});
};
ko.bindingHandlers.fadeVisible = {
init: function(element, valueAccessor) {
var value = valueAccessor();
$(element).hide().html(ko.utils.unwrapObservable(value)).fadeIn();
},
update: function(element, valueAccessor) {
var value = valueAccessor();
$(element).hide().html(ko.utils.unwrapObservable(value)).fadeIn();
}
};
ko.applyBindings(new Model ());
EDIT
My initial response did not fade out, wait, and then fade back in. Here is an updated fadeVisible binding handler
ko.bindingHandlers.fadeVisible = {
update: function(element, valueAccessor) {
var value = valueAccessor();
$(element).fadeOut('slow', function () {
$(element).html(ko.utils.unwrapObservable(value)).fadeIn();
});
}
};
Problem
In trying to spice up a knockout.js UI with effects, I've found that I often have several sections that alternate based on a conditional. An example of this could be a details pane in a list view that displays instructions when no element is selected. This works great declarativly using the visible binding - but it falls short when you attempt to add animations to the mix, since there's no chaining of the show / hide animations. I've simplified the animation knockout.js example here to demonstrate: http://jsfiddle.net/yq5rS/ While I could probably hack something, I'm looking for a more idiomatic knockout.js way of doing this kind of chaining. I've considered a few solutions: - Having a container element with a custom binding that captures the conditional and which element to show in the on and off states. - Having the "animation visible" binding dependent on both the conditional and a function that checks if the other element is hidden. Edit: To be clear, I want the fade out of one element to happen before the fade in of the other. Thanks Josh.