Skip to content

Instantly share code, notes, and snippets.

@kevinsimper
Created May 13, 2014 10:04
Show Gist options
  • Save kevinsimper/d6643a74a7a24a09f2d6 to your computer and use it in GitHub Desktop.
Save kevinsimper/d6643a74a7a24a09f2d6 to your computer and use it in GitHub Desktop.
Knockout.js .slideDown() binding with jQuery
// Here's a custom Knockout binding that makes elements shown/hidden via jQuery's slideDown()/slideUp() methods
// Could be stored in a separate utility library
ko.bindingHandlers.slideToggle = {
init: function(element, valueAccessor) {
// Initially set the element to be instantly visible/hidden depending on the value
var value = valueAccessor();
$(element).toggle(ko.utils.unwrapObservable(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
},
update: function(element, valueAccessor) {
// Whenever the value subsequently changes, slowly slide the element down or up
var value = valueAccessor();
ko.utils.unwrapObservable(value) ? $(element).slideDown() : $(element).slideUp();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment